如何在 Angular 中动态添加额外的路由

D. *_*erg 11 typescript angular-routing angular angular-router angular5

我在 Angular-CLI 和 .NET Core 2.0 中使用 Angular 5.2.2(打字稿)。

我正在尝试向我的应用程序动态添加其他路由。

这个想法是我从服务器动态获取我的路由,该服务器检查哪些模块应该可供用户使用。但我似乎无法获得可用的路线。

我尝试使用添加它们,RouterModule.forRoot但这不起作用。

我试过使用,Router.resetConfig但我似乎无法让它工作。我尝试使用依赖注入在我创建的函数中获取它,但我最终得到了循环依赖:

Uncaught Error: Provider parse errors:
Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
Run Code Online (Sandbox Code Playgroud)

这是我拥有的一些代码:

app-routing.module.ts

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { Routes, RouterModule, Router } from '@angular/router';

var routes: Routes = [{ path: '', loadChildren: "../app/modules/f2p-dashboard/f2p-dashboard.module#F2PDashboardModule" }];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: AppConfigServiceFactory,
      deps: [F2PModuleService, Router ],
      multi: true
    }
  ]
})

export function AppConfigServiceFactory(moduleService: F2PModuleService, 
router:Router) {
  return () => {
    return moduleService.Init().subscribe((result) => {
      let additionalRoutes = moduleService.GetRoutes()
      routes = routes.concat(additionalRoutes);
      console.log(routes);
      //routes is filled
  router.resetConfig(routes);
  //RouterModule.forRoot(routes);
});
Run Code Online (Sandbox Code Playgroud)

编辑:我尝试添加的所有路线都使用 loadChildren

小智 13

一种方法是将路由推送到路由器并使用 resetConfig。

Example :
constructor(private router: Router, private route: ActivatedRoute) {}
   const config = this.router.config;
   config.push({
            path: 'dynamicRoutePath',
            component: DynamicRouteComponent,
        });
        this.router.resetConfig(config);
        this.router.navigate(['dynamicRoutePath'], {relativeTo: this.route});
Run Code Online (Sandbox Code Playgroud)

这应该有效。