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

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

    You can try using interval if that is more convenient. Calling subscribe gives you Subscription that lets you cancel the polling after sometime.

    let observer = Observable.interval(1000 * 4);
    let subscription = observer.subsscribe(x => {
        this._http.get(this._url)
         .share()
         .map(this.extractData)
         .catch(this.handleError)
    });
    
    ....
    // if you don't require to poll anymore..
    subscription.unsubscribe();
    

提交回复
热议问题