Yuvals
Yuvals

Reputation: 3266

Angular AOT: Function calls are not supported

I am trying to create dynamic routes array for RouterModule. As explained in don't and do's, I am exporting a function to use as my routes array:

export function DynamicRoutingCreation() {
  let myRoutes;
  // .. forEach loop to create dynamic array

}

and in my AppModule:

    const APP_ROUTES: Routes = DynamicRoutingCreation();
...

RouterModule.forRoot(APP_ROUTES)

But I keep getting this error:

Error ... Calling function 'DynamicRoutingCreation' , function calls are not supported. Consider replacing the function or lambda with a reference to an exported function.

Upvotes: 0

Views: 676

Answers (2)

Lukáš Pikora
Lukáš Pikora

Reputation: 194

This can be solved by providing routes definition to ROUTES using function factory... (tested on Angular 4.1.2)

Modify your AppModule (app.module.ts):

change RouterModul.forRoot in imports array

imports: [
RouterModule.forRoot(routes)
...

to

RouterModule.forRoot([])

add this two providers in providers array:

... ANALYZE_FOR_ENTRY_COMPONENTS
} from '@angular/core';
...  ROUTES,
} from '@angular/router';
...
providers: [
{provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes},
{provide: ROUTES, multi: true, useFactory: getRoutes},
...

define factory function (at top of the app.module.ts file):

export function getRoutes() {
  return routes;
}

maybe you need also create new file eg: app.routes.ts and put your dynamic routes definitions there eg.:

export let routes: Routes = [
            {
                path: '',
...
routes.push(objwithsome new route) etc..
...

and import it in AppModule (app.module.ts).

import { routes } from './app.routes';

Upvotes: 0

Yuvals
Yuvals

Reputation: 3266

I found a workaround for this - instead of passing RouterModule a function reference , I did the following :

inside AppModule.ts

..
RouterModule.forRoot([]) // pass an empty routes
..

later , inside AppComponent, reset the router with dynamic array:

router.resetConfig(/* dynamic function returning routes array */)

That worked without side effects

Upvotes: 3

Related Questions