Search code examples
angularangular-router

Define different routes inside routing.module


I want to define different routes according to a flag. This is part of

app-routing.module.ts

 import { Token } from "...";  //  InjectionToken

 let routes: Routes;
 @NgModule({
   imports: [RouterModule.forRoot(routes)],
   exports: [RouterModule]
})
export class AppRoutingModule {
  constructor(@Inject(Token) private token) {
    if (this.token) {
      routes = [...]
    }
    else {
       routes =[...]
    }
  }

Unfortunately, the above does not work. Any idea how to achieve what I want?


Solution

  • Try to set the router config as below:

    import { Token } from "...";  //  InjectionToken
    
     let routes: Routes;
     @NgModule({
       imports: [RouterModule.forRoot(routes)],
       exports: [RouterModule]
    })
    export class AppRoutingModule {
      constructor(@Inject(Token) private token,
       router: Router) {
        let config = router.config;
        if (this.token) {
          routes = [...]
        }
        else {
           routes =[...]
        }
        config = routes;
        router.resetConfig(config);
      }
    }
    

    A working example here https://stackblitz.com/edit/angular-emnqvb