路由器的动态设置

Dynamic Setting of the Router

我有一个 Angular 5 应用程序可以从 Contentful 检索内容。其中一些内容是路线。我想将这些设置在子 RoutingModule 中,如下所示:

const myRoutes: Routes = [
  { path: '', component: BaseComponent },
  { path: '**', component: FailComponent }
];

@NgModule({ 
  RouterModule.forChild(myRoutes),
  ... 
})

export class MyRoutingModule {
  routesFromContentful = retrieveRoutesFromContentful();
  routes.forEach((route:string) => {
    myRoutes.push({ path: route, component: GenericComponent }); 
  }
}

要明确:

  1. 我正在将所有路由映射到同一个组件,GenericComponent。这是故意的。
  2. 我从 Contentful 检索路线没问题。
  3. 问题是我推入 myRoutes 的新路线无法识别。

有没有办法识别这些路线?是不是因为导出的 class 在 @NgModule 之后才被识别?

要将路由推送到当前路由配置,您可以通过调用 router 依赖实例上的 resetConfig 方法来推送这些路由,如下所示。

export class MyRoutingModule {
  constructor(private router: Router){
     this.loadRoutes();
  }

  loadRoutes(){
     routesFromContentful = retrieveRoutesFromContentful();
     routes.forEach((route:string) => {
        myRoutes.push({ path: route, component: GenericComponent }); 
     }
     //reseting router configuration
     this.router.resetConfig(routes);
  } 
}

或者您可以直接在 router.config 对象中推送新路由。

export class MyRoutingModule {
  constructor(private router: Router){
     this.loadRoutes();
  }

  loadRoutes(){
     routesFromContentful = retrieveRoutesFromContentful();
     routes.forEach((route:string) => {
        //adding routes to existing to configuration.
        this.router.config.push({ path: route, component: GenericComponent }); 
     }
  } 
}