Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delaying Angular application start until promise resolves?

Tags:

angular

Currently, I have this:

new Loader().load().then(() => {
    platformBrowserDynamic().bootstrapModule(AppModule);
  });

The problem is that I don't necessarily need to delay everything until the promise resolves, just ngOnInit and any route resolving. I'd like to allow any other angular2 setup that ISN'T routing or rendering, but block those until a promise resolves. Is there a more efficient way to do this?

like image 582
Stefan Kendall Avatar asked Oct 22 '25 15:10

Stefan Kendall


1 Answers

Using APP_INITIALIZER

First option would be to use the APP_INITIALIZER. With this you can do initial stuff, before the AppComponent gets bootstrapped:

@NgModule({
    // ...
    providers: [
        {
            provide: APP_INITIALIZER, 
            useFactory: appInitFactory, 
            deps: [AppInitService],
            multi: true
        }
    ]
})
export class AppModule {}

With the deps array you can inject services you might need inside your factory:

export function appInitFactory(appInitService: AppInitService): () => Promise<any> {
    return () => appInitService.initializeApplication();
}

You have to return an (arrow) function with this.

Using the Router config

Second option, if you use the Router is to set the initialNavigation to false in your forRoot call on the RouterModule:

@NgModule({
    imports: [
       RouterModule.forRoot(AppRoutes, {initialNavigation: false})
    ]    
})
export class AppModule {}

Then inside your AppComponent you should have some service which does the Promise logic for you, and navigate where you want to go after its done. The 'problem' with this solution is that the AppComponent does get initialised, but if you only mind about the actual routes not getting resolved immediately, but do have sort of an app-shell while you wait for the resolving, you can use this

like image 150
Poul Kruijt Avatar answered Oct 25 '25 07:10

Poul Kruijt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!