Consider the typical HttpClient example
In Service
config: string[];
load(): Observable<string[]> {
return this.http.get<string[]>('./assets/config.json');
}
getConfig(key: string): string {
if (!this.config) {
this.load.subscribe(data => this.config = data);
}
return this.config[key];
}
In Component
value = myService.getConfig('blah');
Obviously, this example doesn't work because return
in getConfig()
happens before config
is getting populated in subscribe()
.
All examples show subscribe()
in the calling component. But how do I await the return inside the service?
NOTE This is just MCVE. In reality, the use case is much more complex and is not how to get the values before application starts. For example, I need to get a large array from the server, and in the service filter based on some criteria and return to component.