使用Observables时间间隔的Angular 5 HTTP请求,而值可能会更改

时间:2018-05-06 20:05:27

标签: typescript rxjs observable angular5

如何正确实现此功能,以便只订阅给定的最新值? - 使用简单的setInterval它对我来说很好,但我想切换到Observables以更好地理解它。

问题显然是我订阅了两次,如果我完成了对函数的订阅,它仍然会触发间隔订阅而我无法完成它,因为我需要它的间隔...

这是我调用数据的组件(cityName可以根据用户输入随时更改,因此更改http发出的请求

submitData2(cityName) {
Observable.timer(0, 10000)
.takeWhile(() => this.alive) // only fires when component is alive
.subscribe(() => {

  this._weatherService.getWeather(cityName)
  .subscribe(weathers => {
     this.weathers = weathers;

    console.log(weathers);
    this.currentImg();
  },
     err => {console.log(err)},
     () => {console.log('end')}

);

});
 }

这是根据城市名称发出请求的服务:

  getWeather(city): Observable<any[]> {
return this.http.get('weather/getCity/' + city)
  .map(res => res.json())     ;
}

1 个答案:

答案 0 :(得分:2)

sub;
submitData2(cityName) {
if (sub) sub.unsubscribe();

sub =
   Observable.timer(0, 10000)
    .takeWhile(() => this.alive) // only fires when component is alive
    .switchMap(() => this._weatherService.getWeather(cityName))
    .subscribe(weathers => {
       this.weathers = weathers;
      console.log(weathers);
      this.currentImg();
    },
    err => {console.log(err)},
    () => {console.log('end')};
 }

这将有效,但您需要在函数调用之外保存订阅,以便在再次调用它时可以清理它。如果你不想清理它并希望保持所有的调用,直到takeWhile完成,那么你可以删除该代码。