skip to Main Content

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


  1. Chosen as BEST ANSWER

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

  2. 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');
    
          })
        );
      }
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search