Angular2: create and destroy a timer

I'm trying to create a timer that will send a GET request every 5 seconds, I will succeed, but I notice that if I go to another page (routing), the timer still works, so I tried to add ngOnDestroy, but I don't have a method unsubscribe

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"

+7
angular observable
source share
2 answers

subscription to observable returns the 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(); } } 
+19
source share

Just unsubscribe

 ngOnDestroy() { this.myObservable.unsubscribe(); } 

Where myObservable is the object returned by subscribe() .

refrence: angular2 is the best way to end the observed interval when the path changes

+1
source share