Currently when bootstrapping the app component angular2 doesn't wait for completion of all the lifecycle phases.
The following method start end sequence will be printed to the console:
AppComponent.ngOnInit() - START
SearchComponent.ngOnInit() - START
AppComponent.ngOnInit() - END
How can for the completion of all the lifecycle phases of app component be waited for, so that the sequence looks as follows:
AppComponent.ngOnInit() - START
AppComponent.ngOnInit() - END
SearchComponent.ngOnInit() - START
You can not control the lifecycle callbacks.
You can use
*ngIf
to not show parts of the application until the condition changes to true
. If you wrap the content of the root component template with such an *ngIf="isLoaded"
no component except the root component will be created.
Route guards to prevent route navigation until a condition becomes true
.
APP_INITIALIZER
that prevents initialization of your Angular2 application until the returned Promise
resolves. See How to pass parameters rendered from backend to angular2 bootstrap method for an example
Observables to notify about state changes and also to cache responses to prevent multiple calls. See What is the correct way to share the result of an Angular 2 Http network call in RxJs 5? for an example.
The chosen way for my problem was the usage of the APP_INITIALIZER. Services utilizing the router (such as Angulartics2) can't be used, because at this point the router hasn't been initialized yet. Below is an example code using async-await.
@NgModule({
imports: [
HttpModule,
routing,
SharedModule.forRoot()
],
providers: [
{provide: APP_BASE_HREF, useValue: '/'},
{provide: APP_INITIALIZER,
useFactory: (appModule:AppModule) => async () => {
await appModule.init();
}, deps: [AppModule], multi:true}
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(private service:Service) {
}
// tslint:disable-next-line:typedef
async init() {
await this.service.init();
}
}