考虑典型的 HttpClient 示例
服务中
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];
}
在组件中
value = myService.getConfig('blah');
显然,这个例子不起作用,因为return
ingetConfig()
发生之前config
被填充到subscribe()
.
所有示例都显示subscribe()
在调用组件中。但是我如何在服务内等待返回?
注意这只是 MCVE。实际上,用例要复杂得多,而不是如何在应用程序启动之前获取值。例如,我需要从服务器获取一个大数组,并在服务中根据一些条件过滤并返回组件。