I start a interval in an Angular component, but it keeps making requests even after I change the route. How can I stop the interval?
//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())
}
You should save subscription to observable:
this.subscription = getAllPolls().subscribe(...);
And implement OnDestroy interface:
ngOnDestroy() {
this.subscription.unsubscribe();
}
来源:https://stackoverflow.com/questions/36582997/end-observable-interval-when-route-changes-in-angular