David Herod David Herod - 3 months ago 22
Javascript Question

Angular 2 Http polling not delivering errors

I am trying to poll a REST API to update a data table which is working fine with the following code:

pollData(url, interval) {
return Rx.Observable.interval(interval)
.mergeMap(() => this.http.get(url));

// get data
this.dataService.pollData(this.url, this.updateInterval)
data => console.log(data),
err => console.log(err),
() => console.log('done'));

The problem is that error and complete never get called. Any suggestions to get this working with onError and onCompete would be greatly appreciated. Thanks!


About the onComplete call on the observer, it will be effected only when the source observable finishes. This means when the observable returned by pollData completes. As you are currently polling with no exit condition, then naturally your observable never completes.

To have this observable complete, you need to come up with an exit condition :

  • timeout (for instance, poll for X seconds, then stop polling)
  • number of polls
  • pollData-based condition (for instance, if no changes detected after X consecutive polling)
  • external completion signal
  • any other condition which makes sense to your use case

All these conditions are easy to implement with RxJS through they will require you to update the code of the pollData function.

For instance for the external completion signal, you could write :

// defining somewhere the subject for signalling end of polling
stopPollingS = new Rx.Subject();

// somehow pass this subject as a parameter of the polling function
pollData(url, interval, stopPollingS) {
return Rx.Observable
         .mergeMap(() => this.http.get(url))

// somewhere in your code when you want to stop polling

About the onError call on the observer, , I am not sure I get what is happening. Have you tried provoking an error and check the onError handler of your observer is indeed called? If there is no error, it is quite obvious that the onError will not be called.