Wait for subscription to complete

2019-02-25 09:18发布

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) .

Service:

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

Client Subscription:

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

1条回答
我想做一个坏孩纸
2楼-- · 2019-02-25 09:44

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

    }
查看更多
登录 后发表回答