Reputation: 12025
How stop interval when you move to another component in Angular 7:
public s: Observable<any>;
this.s = interval(5000)
.pipe(takeWhile(() => this.visitors.length > 0))
.subscribe(() => {});
I tried to stop interval in component destructor:
ngOnDestroy() {
this.s.unsubscribe();
}
Upvotes: 1
Views: 3850
Reputation: 4199
You made 2 mistakes; let me describe them:
subscribe()
function doesn't return Observable
; pipe
returns.unsubscribe
won't stop the interval.I Use setInterval
instead of interval like:
timer: any;
ngOnInit() {
this.timer = setInterval(() => {
// here do whatever you want every 5 seconds
}, 5000);
}
And use clearInterval
function onDestroy; like:
ngOnDestroy() {
clearInterval(this.timer);
}
Upvotes: 3