It is possible to execute asynchronous task before the app start by providing a function returning promise using APP_INITIALIZER
token.
@NgModule({
providers: [
{
provide: APP_INITIALIZER,
useValue: functionReturningPromise
multi: true
},
})
export class AppModule {}
file:app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule],
providers: [
{
provide: APP_INITIALIZER,
useValue: ()=>new Promise(resolve => {
// LOL, this app will never load.
// don't do it in prod!
window.setTimeout(resolve, 1000000);
}),
multi: true
}
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
翻译自:https://www.30secondsofcode.org/angular/s/using-app_initializer-to-delay-app-start