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

前端 未结 4 2038
攒了一身酷
攒了一身酷 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:02

    Update to RxJS 6

    import { timer } from 'rxjs';
    import { concatMap, map, expand, catchError } from 'rxjs/operators';
    
    pollData$ = this._http.get(this._url)
      .pipe(
        map(this.extractData),
        catchError(this.handleError)
      );
    
    pollData$.pipe(
      expand(_ => timer(4000).pipe(concatMap(_ => pollData$)))
    ).subscribe();
    

    I'm using RxJS 5 and I'm not sure what the RxJS 4 equivalent operators are. Anyway here is my RxJS 5 solution, hope it helps:

    var pollData = this._http.get(this._url)
                .map(this.extractData)
                .catch(this.handleError);
    pollData.expand(
      () => Observable.timer(4000).concatMap(() => pollData)
    ).subscribe();
    

    The expand operator will emit the data and recursively start a new Observable with each emission

提交回复
热议问题