在Angular中动态添加路线 [英] Dynamically adding routes in Angular

查看:66
本文介绍了在Angular中动态添加路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的角度应用程序中动态添加路线

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 {
}

这在dev中工作正常,但在生产版本中未添加动态路由.我尝试使用工厂来确保添加了路由,但是使用函数调用无法构建该路由.

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 }
];

如果我访问 http://myap.com/firstsection ,则效果很好. 然后,如果我转到 http://myap.com/secondsection ,即使该网址是改变了.

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.

如果我随后转到 http://myap.com/oneofmystaticroutes ,然后转到

If I then go to http://myap.com/oneofmystaticroutes then to http://myap.com/secondsection it works fine.

推荐答案

我认为问题出在AOT中.

I think the problem is somewhere in AOT.

我的建议是将路由配置移至AppComponent. 注入路由器和路由,然后添加所需的路由,然后尝试使用 resetConfig

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);

这篇关于在Angular中动态添加路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆