In our Angular6 application, we utilize a globalcontextServiceFactory to initialize the application before rendering views.
This process involves subscribing to get configuration from a back-end endpoint and then using forkJoin to retrieve environment application data after launch.
An issue arises with a provider that uses a static variable to store the configuration obtained from the subscription. This provider is set up with provideIn: 'root' injector considering hierarchical dependency injectors.
app.module.ts
export function contextServiceFactory(contextService: ContextService): Function {return () => contextService.init();}
@NgModule({
declarations: [AppComponent],
imports: [...],
providers: [...,
{provide: APP_INITIALIZER, useFactory: contextServiceFactory, deps: [ContextService], multi: true}
],
bootstrap: [AppComponent]
})
export class AppModule {}
context.service.ts
@Injectable()
export class ContextService{
constructor(...){}
init() {
this.configSubscription = this.getConfig().subscribe((config: Config) => {
ConfigService.config = config;
this.globalSubscription = forkJoin(
this.getDatas1(),
this.getDatas2(),
this.getDatas3()
).subscribe((response: Object) => {
this.setDatas1(response[0]),
this.setDatas2(response[1]),
this.setDatas3(response[2])
this.contextInitialized.next(true);
this.inj.get(Router).initialNavigation(); // <-- Init router when all responses are retrieved
});
});
config.service.ts
@Injectable({
providedIn: 'root'
})
export class ConfigService {
private static _configuration: Config;
public static get config(): Config {
return ConfigService._configuration;
}
public static set config(config: Config) {
ConfigService._configuration = config;
}
}
test.service.ts
@Injectable({
providedIn: 'root'
})
export class TestService {
foo: boolean;
constructor(private contextService: ContextService) {
// We encounter an error here because TestService is called after ContextService but before the static variable is initialized by init()
this.foo = ConfigService.config.bar;
}
}
We see this error in the console: "ERROR TypeError: Cannot read property 'bar' of undefined at new TestService (test.service.ts)"
Question: Is it feasible to wait for the application to be fully loaded before utilizing a static value stored in another service?
Thanks