Angular中路径更改时的End Observable间隔

问题描述 投票:2回答:1

我在Angular组件中启动一个间隔,但即使在我更改路径后它也会继续发出请求。我该如何停止间隔?

//returns an observable
getAllPolls() {
    return Observable.interval(2000).switchMap(() => this._http.get('https://xq4kftam4k.execute-api.us-east-1.amazonaws.com/test/polls2'))
        .map((res: Response) => res.json())

}
angular typescript rxjs angular2-routing
1个回答
13
投票

您应该将订阅保存到observable:

this.subscription = getAllPolls().subscribe(...);

并实现OnDestroy接口:

  ngOnDestroy() {
     this.subscription.unsubscribe();
  }
© www.soinside.com 2019 - 2024. All rights reserved.