SpazzMarticus SpazzMarticus - 5 months ago 115
Javascript Question

Repeat request (Angular2 - http.get) n seconds after finished

I played around with angular2 and got stuck after a while.

Using

http.get
works fine for a single request, but I want to poll live-data every 4 seconds, after tinkering for quite a while and reading a lot of reactivex stuff i ended up with:


Observable.timer(0,4000)
.flatMap(
() => this._http.get(this._url)
.share()
.map(this.extractData)
.catch(this.handleError)
)
.share();


Is there a simple way to start a (4 second) interval after the
http.get
-observable has emitted the result of the request? (Or will I end up in observable-hell?)

Timeline i want:


Time(s): 0 - - - - - 1 - - - - - 2 - - - - - 3 - - - - - 4 - - - - - 5 - - - - - 6
Action: Request - - Response - - - - - - - - - - - - - - - - - - - -Request-...
Wait: | wait for 4 seconds -------------------------> |

Answer

I managed to do it myself, with the only downside beeing that http.get can't be repeated more easily.

pollData(): Observable<any> {

  //Creating a subject
  var pollSubject = new Subject<any>();

  //Define the Function which subscribes our pollSubject to a new http.get observable (see _pollLiveData() below)
  var subscribeToNewRequestObservable = () => {
    this._pollLiveData()
      .subscribe(
      (res) => { pollSubject.next(res) }
      );
  };

  //Subscribe our "subscription-function" to custom subject (observable) with 4000ms of delay added
  pollSubject.delay(4000).subscribe(subscribeToNewRequestObservable);

  //Call the "subscription-function" to execute the first request
  subscribeToNewRequestObservable();

  //Return observable of our subject
  return pollSubject.asObservable();

}

private _pollLiveData() {

  var url = 'http://localhost:4711/poll/';

  return this._http.get(url)
    .map(
    (res) => { return res.json(); }
    );
};

Here is why you can't use the more straight forward subscription:

var subscribeToNewRequestObservable = () => {
    this._pollLiveData()
      .subscribe(pollSubject);
  };

The completion the http.get-observable would also complete your subject and prevent it from emitting further items.


This is still a cold observable, so unless you subscribe to it no requests will be made.

this._pollService.pollData().subscribe(
  (res) => { this.count = res.count; }
);
Comments