Reputation: 15104
I'm using the lastest version of Angular and I'm looking for the best way to create and clear an interval.
And I can't find any example of code for clearing an interval.
My component is like this at the moment :
import { Component, OnInit, Injectable, OnDestroy } from '@angular/core';
import { APIService } from '../api.service';
import { Observable, interval } from 'rxjs';
@Component({
selector: 'app-play',
templateUrl: './play.component.html',
styleUrls: ['./play.component.scss']
})
@Injectable()
export class PlayComponent implements OnInit, OnDestroy {
private api: APIService;
private timer: Observable<Number>;
constructor(_api: APIService) {
this.api = _api;
}
ngOnInit() {
this.timer = interval(1000);
this.timer.subscribe(() => this.api.status().subscribe(status => console.log(status)));
}
ngOnDestroy() {
// How to clear interval here ?
}
}
How am I supposed to destroy my interval in the ngOnDestroy
method ? If I don't destroy it, the interval keep running every time i create a new component.
Upvotes: 0
Views: 352
Reputation: 6016
try this, use Subscription
subscription = Subscription[] = [];
ngOnInit() {
this.timer = interval(1000);
this.subscription.push(this.timer.subscribe(() =>
this.api.status().subscribe(status => console.log(status)))
);
}
ngOnDestroy() {
// unsubscribe subscription here
this.subscription.unsubscribe();
}
for more about Subscription
check here
which is explained in detail..
Hope this helps.. :)
Upvotes: 3