等待订阅完成

时间:2017-05-24 15:36:55

标签: angular asynchronous undefined observable subscription

我有一个简单的场景: 我想将从服务返回的数组存储到类变量中。在存储数据之前,如何等待数据可用?如果我等待一段时间(使用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
}

如果我等了一段时间,那么数据是可用的......但如果它......这样就不一定有必要......

ngOnInit(): void {
    this.getEventHistory();
    setTimeout(() => {
      console.log('HeatmapData: '+ this.heatmapData.toString());
    },3000);
  }

1 个答案:

答案 0 :(得分:2)

您可以在complete()函数上执行此操作。这样做可以确保数据首先到达。

    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());
                            );

    }
相关问题