Can OpaqueToken be set via observable?
I am trying to set opaquetoken from vendors using observable. The reason is that I am reading the value through an Http provider (external JSON file).
This is what I am trying to do
{
provide: SOME_OPAQUE_TOKEN,
useFactory: (configService: ConfigService) => {
configService.getPath('campaigns')
.subscribe((res) => {
???
});
},
deps: [ConfigService],
},
So obviously this won't work, but I'm wondering if there is a solution for this kind of problem?
Or if it is actually possible to build a service using useFactory where one of your parameters will be restored asynchronously.
Is it even possible?
Edit: Solution using APP_INITIALIZER
In AppModule:
{
provide: APP_INITIALIZER,
useFactory: (configService: ConfigService) => () => configService.load(),
multi: true,
deps: [ConfigService, Http],
},
In ConfigService load ():
public load(): Promise<Configuration> {
let promise =
this.http
.get('config.json')
.map(m => m.json())
.toPromise();
promise
.then(config => this.appConfig = config);
return promise;
}
Once we have installed appConfig, we can use it to set the OpaqueToken:
{
provide: BASE_PATH,
useFactory: (configService: ConfigService) => configService.appConfig.basePath, deps: [ConfigService],
},
source to share
APP_INITIALIZER
It is intended that an undocumented multi-provider will be used to resolve application dependencies asynchronously.
The initializer is supposed to be a function that returns a promise (for async initialization) or any other value (for synchronization initialization). Since it APP_INITIALIZER
is a multi-provider, there can be many initializers, they will be executed in parallel and expected. The implementation is here .
It can be defined as a provider in a module:
{
provide: APP_INITIALIZER,
useFactory: (...deps...) => () => promise,
deps: [...deps...],
multi: true
}
Or for an initializer without dependencies:
{
provide: APP_INITIALIZER,
useValue: () => promise,
multi: true
}
source to share