我在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())
}
答案 0 :(得分:12)
您应该将订阅保存到observable:
this.subscription = getAllPolls().subscribe(...);
并实现OnDestroy接口:
ngOnDestroy() {
this.subscription.unsubscribe();
}