1

I have an url pattern to the same location but it ends with different data.

Example:

Keep in mind that "detail" and "object" both are dynamic, example: detail1-category, detail2-category, detail3-category, object1, object2, objectt3.

URL1 = /url/detail-category

URL2 = /url/object

I need to loadChildren based on whether the URL ends with "-category" or not, I am using matcher but I loose the "path" variable since matcher and path can't be used at the same time.

Original:

{ path: 'url/:id',  
    loadChildren: './modules/child.module#ChildModule'
},

Updated:

{ matcher: categoriesMatcher, 
    loadChildren: './modules/child.module#ChildModule'
},

export function categoriesMatcher(url: UrlSegment[]) {
    return url.length === 1 && url[0].path.endsWith('-category') ? ({consumed: url, path: url}) : null;
  }

// the above partially taken from here, and it works but we lose the data which dictates the behavior of the component. Angular 2 different components with same route

Helmut Granda
  • 4,565
  • 7
  • 35
  • 51
  • 1
    I don't understand what you mean by "path" variable. Are you referring to the parameter `:id` in the original example? These parameters are assigned to the `posParam` of the match result. Here is an example: https://gist.github.com/anein/fba647b4206695d109c30e1fc0d2e8ee – Reactgular Jun 05 '18 at 17:54
  • Yeah, that is what I meant. I was pretty close by looking at "snapshot". I was about to try to inject it with snapshot.paramMap... Glad you beat me to it! – Helmut Granda Jun 05 '18 at 18:02
  • Can you set your comment as an answer so that I can give you credit? – Helmut Granda Jun 05 '18 at 18:02

1 Answers1

1

A matcher can provide parameters as part of the matching logic. The return value should contain a posParam property with the values of each route parameter.

For example:

export function MyAwesomeMatcher ( url: UrlSegment[] ): UrlMatchResult {
    if (url.length === 0) {
        return null;
    }
    const reg = /^(awesome-path)$/;
    const param = url[ 0 ].toString();
    if (param.match( reg )) {
       // myValue: "awesome-path"
       return ({ consumed: url, posParams: { myValue: url[ 0 ] } });
   }
   return null;
}

// define application routes.
const routes: Routes = [
   { path: '', component: HomeComponent, pathMatch: 'full' },
   { matcher: MyAwesomeMatcher, component: MyAwesomeComponent }
   ...
];

Code for above example copied from here:

https://gist.github.com/anein/fba647b4206695d109c30e1fc0d2e8ee

Reactgular
  • 52,335
  • 19
  • 158
  • 208