I create an angular6 library call mapModule, and be imported into app module, now I want to do something before load mapModule, so I try to add APP_INITIALIZER in this library :
export function StartupServiceFactory2(mapConfigService: MapConfigService) {
const x = 2 + 2;
console.log(x);
return () => mapConfigService.readConfig();
}
but it doesn't work
Do you provide it?
// app.module
providers: [
{ provide: APP_INITIALIZER,
useFactory: StartupServiceFactory2,
deps: [MapConfigService], multi: true }
]
Does mapConfigService.readConfig()
return Promise
?
Take a look at example
I have run into it as well, where APP_INITIALIZER
wouldn't completely initialize the app before triggering CanActivate
route guard.
Few things to look out for:
mapConfigService
should return Promise
Observable
to promise via toPromise()
and subsequently calling .then()
- the promise is released before tapping into .then()
:This will have issue:
let promise = this.mapConfigService.map(...).toPromise().then(()=>{
/// this part of the code will NOT block the APP_INITIALIZER
/// meaning when toPromise() is called the promise is released
/// right away before having a chance to fully execute the .then() part
....
});
Instead wrap the Observable
into Promise
and have the resolve()
release the promise, like following:
readConfig(): Promise<any> {
const promise = new Promise((resolve, reject) => {
this.mapConfigService.subscribe((data)=> {
// additional stuff
resolve();
return data;
});
return promise;
}
Hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.