I am trying to create timer, that will send GET request every 5 seconds, I manage to do it, but I notice that if I move to different page (routing) the timer still running, so I tried to add ngOnDestroy, but I don't have the "unsubscribe" method
import {Component, OnInit, OnDestroy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
templateUrl: 'app/pages/CurrentRuns/currentruns.component.html'
})
export class CurrentRunsComponent implements OnInit, OnDestroy {
private timer;
ticks=0;
ngOnInit() {
this.timer = Observable.timer(2000,5000);
this.timer.subscribe(t => this.tickerFunc(t));
}
tickerFunc(tick){
console.log(this);
this.ticks = tick
}
ngOnDestroy(){
console.log("Destroy timer");
}
}
I am using angular2 RC7, "rxjs": "5.0.0-beta.12"
In my case when I visit to another page it stops but when I came back to this page then 2 timers starts like says @user3145373 in comment above.
So the solution is to make the value timer null in ngOnDestroy like this:
export class CurrentRunsComponent implements OnInit, OnDestroy {
ticks = 0;
private timer;
// Subscription object
private sub: Subscription;
ngOnInit() {
this.timer = Observable.timer(2000,5000);
// subscribing to a observable returns a subscription object
this.sub = this.timer.subscribe(t => this.tickerFunc(t));
}
tickerFunc(tick){
console.log(this);
this.ticks = tick
}
ngOnDestroy(){
console.log("Destroy timer");
// unsubscribe here
this.sub.unsubscribe();
this.timer = null
}
}
subscribing to a observable returns a subscription object
import {Component, OnInit, OnDestroy} from '@angular/core';
import { Observable, Subscription } from 'rxjs/Rx';
@Component({
templateUrl: 'app/pages/CurrentRuns/currentruns.component.html'
})
export class CurrentRunsComponent implements OnInit, OnDestroy {
ticks = 0;
private timer;
// Subscription object
private sub: Subscription;
ngOnInit() {
this.timer = Observable.timer(2000,5000);
// subscribing to a observable returns a subscription object
this.sub = this.timer.subscribe(t => this.tickerFunc(t));
}
tickerFunc(tick){
console.log(this);
this.ticks = tick
}
ngOnDestroy(){
console.log("Destroy timer");
// unsubscribe here
this.sub.unsubscribe();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With