问题
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