angularjsangular-routingdynamic-routing

Dynamic routing in angular based on a condition


I want my app to route to different components based on an environment variable(e.g. switch). In the constructor of app routing module , I have added the condition to check for the variable.

if(switch === 'ON'){
    router.resetConfig(route1);
 }
else if(switch === 'OFF'){
   router.resetConfig(route2);
 }

In the ngDoBootstrap method of AppModule, I am calling the backend to get the value of environment variable.

Now the problem is, when I load the app for the first time, constructor of app routing module is getting called first and then the backend call is happening. I want to wait for the backend call to fetch the value of switch and then execute the condition written in the constructor.

However, after refreshing the page again, it routes to the correct path.

I tried setting timeout in the constructor, It works but that is not the correct way though.

Any help would be greatly appreciated.


Solution

  • You need to use APP_INITIALIZER to perform the configuration before the application loads.

    import { APP_INITIALIZER, NgModule } from '@angular/core';
    import { take } from 'rxjs';
    
    ...
    
    ...
    
    @NgModule({
      ...
      providers: [
        {
          provide: APP_INITIALIZER,
          multi: true,
          useFactory: (http: HttpService, router: Router) => {
            return () => http.get('/api-route').pipe(
                             take(1),
                             tap((data) => {
                                  if(switch === 'ON'){
                                      router.resetConfig(route1);
                                  } else if(switch === 'OFF'){
                                      router.resetConfig(route2);
                                  }
                             })
                         );
          },
          deps: [HttpService, Router],
        },
      ],
      ...
    })
    export class AppModule {}
    

    Reference Article