Postpone service injection after APP_INITIALIZER

久未见 提交于 2020-02-06 07:56:10

问题


I needed to do an API call before bootstrapping my Angular app, to get user info that are required. I followed this answer, updating the call to the last version of Angular, and it worked.

My problem is that the service used in the useFactory function is injected in other components and seems that, despite the bootstrap happens after the initialization, the injection happens when the service data is not ready yet.

In app.module.ts

export function startupServiceFactory(startup_service: StartupService) {
  return () => startup_service.load();
}

providers: [
    StartupService,
    {
      provide: APP_INITIALIZER,
      useFactory: startupServiceFactory,
      deps: [StartupService],
      multi: true
    },
...

In app.component.ts

if(!this.startup_service.startup_data){
      console.log(this.startup_service.startup_data);
    }

In startup.service.ts

load(): Promise<any>{
    return this.httpClient.get<any>('APICALL').pipe(
      tap(
        result => {
          this.startup_data = result;
          console.log(this.startup_data);
        }
      )
    ).toPromise();
  }

The console.log in startup service happens correctly before that in app.component and shows that startup_data has data, but when app.component reads this.startup_service.startup_data it gives undefined. Other injections that happen long after the initialization have access correctly to that variable.

Is there any way I can make all components wait for initialization to finish before they inject the service that makes that call?

来源:https://stackoverflow.com/questions/59735520/postpone-service-injection-after-app-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!