Dynamically adding routes in Angular

2019-05-29 21:44发布

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.

1条回答
ら.Afraid
2楼-- · 2019-05-29 21:51

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

routes.push({ path: section.route, component: SectionComponent });
router.resetConfig(routes);
查看更多
登录 后发表回答