1

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 3

2

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'];
});
Sign up to request clarification or add additional context in comments.

1 Comment

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/…
2

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

The result is of type UrlMatchResult, see angular.io/api/router/UrlMatchResult
0

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');

      })
    );
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.