我创建了一个名为mapModule的angular6库,并导入到应用模块中,现在我想在加载mapModule之前做一些事情,所以我尝试在此库中添加 APP_INITIALIZER :
export function StartupServiceFactory2(mapConfigService: MapConfigService) {
const x = 2 + 2;
console.log(x);
return () => mapConfigService.readConfig();
}
但这不起作用
答案 0 :(得分:1)
您提供吗?
// app.module
providers: [
{ provide: APP_INITIALIZER,
useFactory: StartupServiceFactory2,
deps: [MapConfigService], multi: true }
]
mapConfigService.readConfig()是否返回Promise
?
看看example
答案 1 :(得分:0)
我也遇到了这种情况,在触发APP_INITIALIZER
路由防护之前,CanActivate
不会完全初始化应用程序。
需要注意的几件事:
mapConfigService
应该返回Promise
Observable
将toPromise()
转换为承诺并随后调用.then()
时-在进入.then()
之前释放承诺:这将出现问题:
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
....
});
相反,将Observable
包装到Promise
中,让resolve()
释放承诺,如下所示:
readConfig(): Promise<any> {
const promise = new Promise((resolve, reject) => {
this.mapConfigService.subscribe((data)=> {
// additional stuff
resolve();
return data;
});
return promise;
}
希望有帮助。