当 Angular 中的路线发生变化时结束可观察间隔

2023-12-04

我在 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();
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 Angular 中的路线发生变化时结束可观察间隔 的相关文章