3

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);
  }
Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
jibjapda
  • 87
  • 2
  • 2
  • 9
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 May 24 '17 at 16:15
  • 1
    Your code structure is flawed. Your `getEventHistory()` method should return an observable (i.e. DO NOT subscribe inside that method). You should only subscribe when you need the data, which in your case is in the `ngOnInit()`. – AngularChef May 24 '17 at 19:48

1 Answers1

2

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

    }
  • Hi thank you for you're reply, I have already tried this, and it does not work. Also with assigning a temporary variable while processing data and then saving it to the member variable. For some reason oncomplete is never called, at least there is no output. – jibjapda May 24 '17 at 15:52
  • Complete function isn't fired? so extrange – Llorenç Pujol Ferriol May 25 '17 at 09:21