Search code examples
angularangular2-services

How to serialize initialization of angular2 components?


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


Solution

  • You can not control the lifecycle callbacks.

    You can use

    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();
        }
    }