0

I'm trying to use a closure to pass parameters to the router matcher.

export function componentMatcher(component) {
    return (url) => {
       // check some condition using component
       return {
           consumed: url
       };
       return null;
    }
};

RouterModule.forChild([
    {
        matcher: componentMatcher('foo'),
        redirectTo: 'foo'

This fails when compiling to AOT with:

ERROR in Error during template compile of 'ComponentPageModule'
  Function expressions are not supported in decorators in 'ɵ0'
    'ɵ0' contains the error at src/app/example-components/component-page/component-page.module.ts(31,30)
      Consider changing the function expression into an exported function.

Without the parameter requirement it's pretty simple to fix:

export function componentMatcher(url) => {
    // check some condition using component
    return {
        consumed: url
    };
    return null;
 }

How can I pass a parameter and make this AOT compliant?

dex
  • 275
  • 1
  • 4
  • 10

1 Answers1

1

You'll parse the URL to check if it matches the pattern you want, and you’ll return the consumed URL, along with the custom route parameter.

RouterModule.forRoot([
  {
    matcher: (url) => {
      if (url.length === 1 && url[0].path.match(/^@[\w]+$/gm)) {
        return {
          consumed: url,
          posParams: {
            username: new UrlSegment(url[0].path.substr(1), {})
          }
        };
      }
      return null;
    },
    component: ProfileComponent
  }
])

The example above checks to see that there is only one segment in the array, then uses regex to make sure the format of the username is a match. When it matches, it returns the entire URL consumed, and defines the username route parameter as a sub-string of the path. If there is no match, it returns null and the router continues to look for other routes that may match the URL. This works just as other routes do, allow you to define child routes, or even lazy loaded routes.

Custom Route Matching with the Angular Router

Taras Kovalenko
  • 2,323
  • 3
  • 24
  • 49