Angular 2:动态追加子路线

时间:2017-01-06 04:02:27

标签: angular angular2-routing

我想知道是否可以在运行时动态附加子路由,比如说服务......?

鉴于:

const routes: Routes = [
    {
        path: '', component: GloriousComponent,
        children: [
           { path: 'path1', component: Child1Component },
           { path: 'path2', component: Child2Component },
           { path: 'path3', component: Child3Component },
        ]
    }
];

我可以删除'的孩子。 '路径以某种方式获取对const路由的引用,然后动态地将子项附加到' '路径?

有些事情......

const routes: Routes = [
    {
        path: '', component: GloriousComponent           
    }
];

routes[''].appendChildren(
        [
           { path: 'path1', component: Child1Component },
           { path: 'path2', component: Child2Component },
           { path: 'path3', component: Child3Component },
        ]
    )

2 个答案:

答案 0 :(得分:4)

目前不支持修改,但您可以自己维护路由列表,然后调用

this.router.resetConfig(routes)

将一组新路由加载到路由器中。

答案 1 :(得分:0)

截至目前,实现这一目标很容易。如果要在当前路由中添加子路由,

const childRoute =  {path: 'details', component: DetailsComponent} 
this.route.routeConfig.children.push(childRoute)

其中“this.route”来自构造函数中注入的ActivatedRoute:

constructor(private router: Router, private route:ActivatedRoute) { }

或者,如果您只想向路由器配置添加新路由,请执行以下操作:

this.router.config.push(newRoute)

哪里 newRoute = {path: 'somePath', component: SomeComponent}