Search code examples
angularangular-routercontentful

Dynamic Setting of the Router


I have an Angular 5 app that retrieves content from Contentful. Some of this content is routes. I would like to set these inside a child RoutingModule as follows:

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

To be clear:

  1. I am mapping all routes to the same component, GenericComponent. This is intended.
  2. I have no problem retrieving the routes from Contentful.
  3. The issue is that the new routes I push into myRoutes are not recognized.

Is there a way to have these routes recognized? Are they not recognized because the exported class comes after @NgModule?


Solution

  • For pushing routes to current route configuration, you could push those routes in by calling resetConfig method on router dependency instance like below.

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

    or You can directly push new routes inside router.config object.

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