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

前端 未结 4 2054
攒了一身酷
攒了一身酷 2020-12-15 08:51

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,

4条回答
  •  天命终不由人
    2020-12-15 09:23

    A minor rework of the answer from Can Nguyen, in case you want polling delay to depend on previous request completion status.

    var pollData = () => request()   // make request
        .do(handler, errorHandler)   // handle response data or error
        .ignoreElements()            // ignore request progress notifications
        .materialize();              // wrap error/complete notif-ns into Notification
    
    pollData()                            // get our Observable...
      .expand(                            // ...and recursively map...
        (n) => Rx.Observable              // ...each Notification object...
          .timer(n.error ? 1000 : 5000)   // ...(with delay depending on previous completion status)...
          .concatMap(() => pollData()))   // ...to new Observable
      .subscribe();
    

    Plunk.

    Or alternatively:

    var pollData = () => request()             // make request
        .last()                                // take last progress value
        .catch(() => Rx.Observable.of(null));  // replace error with null-value
    
    pollData()
      .expand(
        (data) => Rx.Observable
          .timer(data ? 5000 : 1000)           // delay depends on a value
          .concatMap(() => pollData()))
      .subscribe((d) => {console.log(d);});    // can subscribe to the value stream at the end
    

    Plunk.

提交回复
热议问题