angularconfigurationangular2-router

Disable application loading/routing in Angular2


I have an angular2 application (RC6 version), where some important global parameters are loaded from a configuration file using a service that collects this file on startup:

@NgModule({
imports:  [ BrowserModule, FormsModule, HttpModule, AppRoutes, SomeCustomModule ],
declarations: [ AppComponent ]
providers: [
            ConfigurationService,
            {
              provide: APP_INITIALIZER,
              useFactory: (config: ConfigurationService) => () => { 
                             return config.load().then(configParams=> { return true;});      
                          },
              deps: [ConfigurationService, HttpModule],
              multi: true
            }
          ],
bootstrap:[ AppComponent ]
})
export class AppModule { }

As shown in this snippet i use what i call a ConfigurationService which through an http call reads a configuration file and returns some parameters (as a Promise). If everything goes well, the application loads perfectly and these config parameters are accessible throughout the sub-modules etc.

The question is, how can i stop application from loading the sub-modules in case this configuration file does not load as expected? (Please note that the AppComponent is in essence just a router-outlet, redirecting to other routes, defined by multiple sub-modules). Can i "disable" or redirect to an error page instead of loading the module/component defined by the requested route?


Solution

  • To disable initial routing of the page, and let it handle depending on your ConfigurationService you have to set initialNavigation to false in your AppRoutes object:

    export const AppRoutes = RouterModule.forRoot(ROUTES, {initialNavigation : false});
    

    Within your ConfigurationService you then have to inject the router and use this to navigate depending on your configuration.

    Another option is to use the canActivate routing hook. Within this hook you can inject the ConfigurationService and let it determine whether it could load this page or not.


    update

    For the latest version of angular, the false value for initialNavigation is deprectated, use 'disabled' instead:

    { initialNavigation : 'disabled' }