【问题标题】:APP_INITIALIZER not work in angular6 libraryAPP_INITIALIZER 在 angular6 库中不起作用
【发布时间】:2019-02-20 22:39:57
【问题描述】:

我创建了一个angular6库调用mapModule,并被导入到app模块中,现在我想在加载mapModule之前做一些事情,所以我尝试在这个库中添加APP_INITIALIZER

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

但它不起作用

【问题讨论】:

    标签: angular angular6


    【解决方案1】:

    我也遇到过,其中APP_INITIALIZER 在触发CanActivate 路由保护之前不会完全初始化应用程序。

    注意事项:

    1. mapConfigService 应该返回 Promise
    2. 当通过toPromise()Observable 转换为promise 并随后调用.then() - 在使用.then() 之前释放promise:

    这会有问题:

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

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      你提供吗?

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

      mapConfigService.readConfig() 是否返回 Promise

      看看example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-21
        • 1970-01-01
        • 2019-10-03
        • 2019-09-18
        • 1970-01-01
        • 2019-06-02
        • 2019-08-10
        相关资源
        最近更新 更多