APP_INITIALIZER在angular6库中不起作用

时间:2018-09-17 03:30:22

标签: angular angular6

我创建了一个名为mapModule的angular6库,并导入到应用模块中,现在我想在加载mapModule之前做一些事情,所以我尝试在此库中添加 APP_INITIALIZER

export function StartupServiceFactory2(mapConfigService: MapConfigService) {
    const x = 2 + 2; 
    console.log(x);
    return () => mapConfigService.readConfig();
}

但这不起作用

2 个答案:

答案 0 :(得分:1)

您提供吗?

// app.module
providers: [
  { provide: APP_INITIALIZER,
   useFactory: StartupServiceFactory2,
   deps: [MapConfigService], multi: true }
]

mapConfigService.readConfig()是否返回Promise

看看example

答案 1 :(得分:0)

我也遇到了这种情况,在触发APP_INITIALIZER路由防护之前,CanActivate不会完全初始化应用程序。

需要注意的几件事:

  1. mapConfigService应该返回Promise
  2. 通过ObservabletoPromise()转换为承诺并随后调用.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;
}   

希望有帮助。