I'm expecting Angular to wait until my loadConfig()
function resolves before constructing other services, but it is not.
app.module.ts
export function initializeConfig(config: AppConfig){
return () => config.loadConfig();
}
@NgModule({
declarations: [...]
providers: [
AppConfig,
{ provide: APP_INITIALIZER, useFactory: initializeConfig, deps: [AppConfig], multi: true }
] })
export class AppModule {
}
app.config.ts
@Injectable()
export class AppConfig {
config: any;
constructor(
private injector: Injector
){
}
public loadConfig() {
const http = this.injector.get(HttpClient);
return new Promise((resolve, reject) => {
http.get('http://mycoolapp.com/env')
.map((res) => res )
.catch((err) => {
console.log("ERROR getting config data", err );
resolve(true);
return Observable.throw(err || 'Server error while getting environment');
})
.subscribe( (configData) => {
console.log("configData: ", configData);
this.config = configData;
resolve(true);
});
});
}
}
some-other-service.ts
@Injectable()
export class SomeOtherService {
constructor(
private appConfig: AppConfig
) {
console.log("This is getting called before appConfig's loadConfig method is resolved!");
}
}
The constructor of SomeOtherService
is getting called before the data is received from the server. This is a problem because then the fields in SomeOtherService
do not get set to their proper values.
How do I ensure SomeOtherService
's constructor gets called only AFTER the loadConfig
's request is resolved?
.catch
there, since the APP_INITIALIZER has it's own catch that stops the APP. Also, use the.toPromise()
from @AlesD answer – Horology