angularroutesangular2-aot

Error during template compile of 'AppRoutingModule' Function expressions are not supported in decorators


I am using the "CaseInsensitiveMatcher" as Alireza put up. Problem is when trying to do a prod build, I am getting the following error

"'urlMatch' references 'CaseInsensitiveMatcher' 'CaseInsensitiveMatcher' contains the error at src\app\providers\caseInsensitiveMatcher.ts(4,10) Consider changing the function expression into an exported function"

Sample Code from App Routing Module

    export function urlMatch(str: string) {
    return CaseInsensitiveMatcher(str).apply(this, arguments);
}

const routes: Routes = [

    { matcher: urlMatch('en-ie'), component: HomepageComponent },
    { matcher: urlMatch('en-gb'), component: HomepageComponent },
]

@NgModule({
    imports: [RouterModule.forRoot(routes),SharedModule, AccountModule],
    exports: [RouterModule, SharedModule, AccountModule]
})
export class AppRoutingModule { }

CaseInsensitveMatcher Code

import {Route, UrlSegment, UrlSegmentGroup} from '@angular/router';

export function CaseInsensitiveMatcher(url: string) {
  return function(
    segments: UrlSegment[],
    segmentGroup: UrlSegmentGroup,
    route: Route
  ) {
    const matchSegments = url.split('/');
    if (
      matchSegments.length > segments.length ||
      (matchSegments.length !== segments.length && route.pathMatch === 'full')
    ) {
      return null;
    }

    const consumed: UrlSegment[] = [];
    const posParams: {[name: string]: UrlSegment} = {};
    for (let index = 0; index < matchSegments.length; ++index) {
      const segment = segments[index].toString().toLowerCase();
      const matchSegment = matchSegments[index];

      if (matchSegment.startsWith(':')) {
        posParams[matchSegment.slice(1)] = segments[index];
        consumed.push(segments[index]);
      } else if (segment.toLowerCase() === matchSegment.toLowerCase()) {
        consumed.push(segments[index]);
      } else {
        return null;
      }
    }

    return { consumed, posParams };
  };
}

I would greatly appreciate if anyone could tell me what I am doing wrong with this? or even how to resolve it. Either way thanks for thanking the time to read

Link To Orginal for Context


Solution

  • CaseInsensitveMatcher returns an anonymous function, but unfortunately Angular does not allow dynamic code like this in AOT. What you can do is to rework your solution so that you only use named exported functions without involving anonymous ones.