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

时间:2016-04-12 20:02:44

标签: angular typescript rxjs angular2-routing

我在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())

}

1 个答案:

答案 0 :(得分:12)

您应该将订阅保存到observable:

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

并实现OnDestroy接口:

  ngOnDestroy() {
     this.subscription.unsubscribe();
  }