Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: create and destroy timer

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"

like image 374
Shay Binyat Avatar asked Sep 18 '16 12:09

Shay Binyat


2 Answers

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

    }
}
like image 182
nourri Avatar answered Nov 03 '22 03:11

nourri


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();

    }
}
like image 42
Luiz Avatar answered Nov 03 '22 02:11

Luiz