我如何才能正确实现这一点,使其只订阅给定的最新值?-使用简单的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()) ; }
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完成之前保留所有调用,那么您可以删除该代码。