I have an Angular 5 app that retrieves content from Contentful. Some of this content is routes. I would like to set these inside a child RoutingModule
as follows:
const myRoutes: Routes = [
{ path: '', component: BaseComponent },
{ path: '**', component: FailComponent }
];
@NgModule({
RouterModule.forChild(myRoutes),
...
})
export class MyRoutingModule {
routesFromContentful = retrieveRoutesFromContentful();
routes.forEach((route:string) => {
myRoutes.push({ path: route, component: GenericComponent });
}
}
To be clear:
GenericComponent
. This is intended.myRoutes
are not recognized. Is there a way to have these routes recognized? Are they not recognized because the exported class comes after @NgModule
?
For pushing routes to current route configuration, you could push those routes in by calling resetConfig
method on router
dependency instance like below.
export class MyRoutingModule {
constructor(private router: Router){
this.loadRoutes();
}
loadRoutes(){
routesFromContentful = retrieveRoutesFromContentful();
routes.forEach((route:string) => {
myRoutes.push({ path: route, component: GenericComponent });
}
//reseting router configuration
this.router.resetConfig(routes);
}
}
or You can directly push new routes inside router.config
object.
export class MyRoutingModule {
constructor(private router: Router){
this.loadRoutes();
}
loadRoutes(){
routesFromContentful = retrieveRoutesFromContentful();
routes.forEach((route:string) => {
//adding routes to existing to configuration.
this.router.config.push({ path: route, component: GenericComponent });
}
}
}