代码之家  ›  专栏  ›  技术社区  ›  makat

角度5 HTTP请求间隔使用可观察值,而值可能会更改

  •  0
  • makat  · 技术社区  · 6 年前

    我如何才能正确实现这一点,使其只订阅给定的最新值?-使用简单的setInterval对我来说效果很好,但我想切换到可观察对象来更好地理解它。

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

    这是我调用数据的组件(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 回复  |  直到 6 年前
        1
  •  2
  •   Brandt    6 年前
    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完成之前保留所有调用,那么您可以删除该代码。