How to extract parameters from complex seo url for eg domain.com/product-samsung-tv-34.html Where 34 is the parameter to be pass to the respective component.
3 Answers
The solution using Angular 6 matcher and regular expression Using UrlMatcher or matcher:
export const routes = [
{ matcher: YourMatcherLogic, component: ProductComponent },
YourMatcherLogic function
// Url matcher for specific logic implementation and extract
parameter using regex.
export function YourMatcherLogic(url: UrlSegment[]) {
// Implement your logic to parse different url segments and extract value as parameters to pass to the component
if ((url.length > 1 && url[1].path.endsWith('.html')) {
let _id = extractIDFromEndsWithHTML(url[1].path); // extractIDFromEndsWithHTML custom function that extracts id from urls 'hello/3.html' using regex
// add id parameters
url[1].parameters = {id: _id};
return {
consumed: url
};
} else {
return null;
}
}
In the component get the extracted parameters as
this.activatedRoute.params.subscribe(params => {
this.productId = params['id'];
});
1 Comment
Filip Cordas
Not the correct way to do it this will add a strange string to the path should not be used. For more info check the default implementation github.com/angular/angular/blob/…
For anyone having to deal with the UrlMatcher.
if (segments.length === 1) {
return {
consumed: segments, posParams: {
id: segments[0]
}
};
}
This is how the default implementation does it.
1 Comment
Benjamin Freitag
The result is of type UrlMatchResult, see angular.io/api/router/UrlMatchResult
You can simply read about that in the Angular router doc Here. Example in your component ngOnInt.
ngOnInit() {
this.heroes$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) => {
// (+) before `params.get()` turns the string into a number
this.selectedId = +params.get('id');
})
);
}