I am trying to dynamically add routes in my angular app
const routes: Routes = [
// my static routes
];
let sections = localStorage.getItem('sections');
if (sections) {
JSON.parse(sections).forEach(section => {
routes.push({ path: section.route, component: SectionComponent });
});
}
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
This works fine in dev but in a production build the dynamic route are not added. I have tried using a factory to make sure that the route are added but it fails build with a function call.
@NgModule({
imports: [RouterModule.forRoot(myRouteFactory())],
exports: [RouterModule]
})
export class AppRoutingModule {
}
I have also tried setting my section component as a default route which mostly works but when I go from one section to the other it doesn't trigger a route change and it stays on the first one.
const routes: Routes = [
{ path: '**', component: SectionComponent }
];
If I go to http://myap.com/firstsection it works fine. Then if I go to http://myap.com/secondsection it stays on the first section even though the url changed.
If I then go to http://myap.com/oneofmystaticroutes then to http://myap.com/secondsection it works fine.
I think the problem is somewhere in AOT.
My suggestion would be move route config to AppComponent. Inject router and routes then append routes you need then try to use resetConfig