Before our Angular application we first have to load some user profile data before the application can be used. First we used some observable magic to do this in our AppModule but there is a much better way; hook into the Angular initialization process using the APP_INITIALIZER token.
Here is a simplified example on how to use it:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NgModule, APP_INITIALIZER } from '@angular/core'; | |
import { HttpClientModule, HttpClient } from "@angular/common/http"; | |
import 'rxjs/add/operator/toPromise'; | |
export function initializeApplication(httpClient: HttpClient): () => Promise<any> { | |
return (): Promise<any> => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(); | |
}, 3000); | |
}); | |
}; | |
} | |
@NgModule({ | |
imports: [HttpClientModule], | |
providers: [ | |
{ provide: APP_INITIALIZER, useFactory: initializeApplication, deps: [HttpClient] multi: true } | |
] | |
}) | |
export class AppModule { } |
Some things to notice:
- You can specify multiple APP_INITIALIZER injection tokens.
- The factory function should return a function that returns a promise
More information: https://hackernoon.com/hook-into-angular-initialization-process-add41a6b7e