【问题标题】:Angular 2: appending child routes dynamicallyAngular 2:动态附加子路由
【发布时间】:2021-05-01 23:51:47
【问题描述】:

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

给定:

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 },
        ]
    )

【问题讨论】:

  • 动态你的意思是在引导程序上?或者当应用程序运行时?
  • 我的意思是在运行时,我更新了我的问题,感谢您指出这一点。
  • 但是你为什么要在运行时做呢?可以举个例子吗?
  • 感谢 Volodymyr,该链接很有帮助。我在运行时添加路由,因为它们可以根据用户行为进行更改。

标签: angular angular2-routing


【解决方案1】:

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

this.router.resetConfig(routes)

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

【讨论】:

    【解决方案2】:

    到目前为止,实现这一点很容易。如果要给当前路由添加子路由,

    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 = {路径:'somePath',组件:SomeComponent}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 2017-04-08
      • 1970-01-01
      • 2017-11-20
      相关资源
      最近更新 更多