Reputation: 1023
I have a simple config service that I've wired with APP_INITIALIZER token in my app.shared.module.ts:
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: (configService: ConfigService) =>
() => configService.getStuff(),
deps: [ConfigService],
multi: true
},
This executes the subscription (config.service.ts):
settings: any;
getStuff() {
this.getSettings()
.subscribe(data => {
this.settings = data);
});
}
getSettings(): Observable<ISettings> {
return (this.httpClient
.get<ISettings>(this.localbaseUrl)
.pipe(
catchError(this.errorHandlerSerevice.handleError)
)) as any;
}
Then I inject this service into other services (through their constructors - which I don't like) and everything works fine on the app start:
constructor(){
this.settings = this.configService.settings;
}
Its fine when I go to the home page and refresh the app from there. The logic is called and data returned. However when I refresh a particular page that uses the component and calls the constructor it seems to late for the data to arrive back, hence I get undefined returned here:
this.settings = this.configService.settings;
I guess the 'wire up' is wrong...
Any suggestions how to tackle it?
Upvotes: 4
Views: 2166
Reputation: 93123
For Angular to wait for your custom APP_INITIALIZER
to complete, it must return a Promise
. Your getStuff
method isn't returning anything, which means Angular won't wait for this.settings
to get set.
You can use toPromise
to convert your Observable
into a Promise
. Here's a basic example:
getStuff(): Promise<void> {
return this.getSettings()
.toPromise()
.then(data => {
this.settings = data;
});
}
Upvotes: 5