等待订阅完成 [英] Wait for subscription to complete
本文介绍了等待订阅完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的场景: 我想将服务返回的数组存储到类变量中.在存储数据之前,如何等待数据可用?如果我等待一定时间(使用settimeout测试),则可以使用此功能.
I have a simple scenario: I want to store an array returned from a service into a class variable. How do I wait for the data to be available until I store the data? It is available if I wait a certain amount of time (tested with settimeout) .
服务:
public getEventHistory(): Observable<heatmapElement[]> {
return this.tokenResolver.getToken(true).switchMap(token => {
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + token);
headers.append('Content-Type', 'application/json');
return this.http.get(this.restApi, new RequestOptions({headers: headers}));
})
.map((res: Response) => res.json());
}
客户订阅:
getEventHistory(): void {
this.eventHistoryService.getEventHistory()
.subscribe(data => this.heatmapData = data,
error => console.log('Error in Heatmap get data: ' + <any> error)
);
console.log('HeatmapData: '+ this.heatmapData.toString()); <---- Undefined and causes error
}
如果我等了一段时间,数据就可用了...但是这样就没必要了……
The data is available if I wait some time... but that shouldn't be necessary in this way should it...
ngOnInit(): void {
this.getEventHistory();
setTimeout(() => {
console.log('HeatmapData: '+ this.heatmapData.toString());
},3000);
}
推荐答案
您可以在complete()函数上执行此操作.这样做将确保数据首先到达.
You can just do it on complete() function. Doing that you will ensure that the data has arrived first.
getEventHistory(): void {
this.eventHistoryService.getEventHistory()
.subscribe(data => this.heatmapData = data,
error => console.log('Error in Heatmap get data: ' + <any> error),
() => console.log('HeatmapData: '+ this.heatmapData.toString());
);
}
这篇关于等待订阅完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文