1

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.

1 Answer 1

0

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

5
  • Thanks for the reply. I tried this but again the value of switch is null at this point.
    – Teeee
    Commented Jul 5 at 13:15
  • @Teeee replace switch with data typo from my side Commented Jul 5 at 13:21
  • ok and this '/api-route' should be the api call to backend?
    – Teeee
    Commented Jul 5 at 13:27
  • @Teeee yes, we read this response and perform the logic Commented Jul 5 at 13:28
  • Sure, unable to upvote though as I am a new contributor.
    – Teeee
    Commented Jul 5 at 14:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.