2

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Strange, works for me. Only extra code I have is injecting routerModule: RouterModule into constructor edited the same. Make sure routes are setup properly.
Something is missing. What about routerModule? Where are you using it? How do we inform RouterModule that we want to change its routes?
@Unknowndeveloper Added a working example url to my answer. Note: the dynamically added routes need to be added in entryComponents in app.module.ts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.