Angular 路线更改时结束可观察间隔

End Observable interval when route changes in Angular

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

}

您应该保存对 observable 的订阅:

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

并实现 OnDestroy 接口:

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