2016-09-18 26 views
7

Her 5 saniyede bir GET isteği gönderecek olan zamanlayıcı oluşturmaya çalışıyorum, bunu yapmayı başarabilirim, ancak farklı sayfaya (yönlendirme) geçmeye devam edersem hala çalışır durumda olduğunu fark ederim. Ben ngOnDestroy eklemeyi denedim, ama "abonelikten çık" yöntemiAngular2: zamanlayıcıyı oluştur ve yok

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

 
    } 
 
} 
 

 
Ben angular2 RC7 kullanıyorum

yok "rxjs": "5.0.0-beta.12"

cevap

19

Gözlemlenebilir abonelik, bir abonelik nesnesini döndürür

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

 
    } 
 
}

+0

merhaba ben bir sorun, sonra 2 zamanlayıcı başlatır var. –

1

Basitçe myObservablesubscribe() tarafından döndürülen nesne olduğu durumlarda

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

abonelikten gerekir.

refrence: Ben durana başka bir sayfaya ziyaret ama ne zaman bu sayfaya geri geldiğinde angular2 - Best way to terminate a observable interval when path changes

+1

Bunu mu demek istediniz: this.timer.unsubscribe(); - abonelikten çıkmıyorum(); this.timer yazarken. –

+1

bir değişken oluşturun "private subscriberObj: Subscription;" ve daha sonra "this.subscriberObj = this.timer.subscribe (t => this.tickerFunc (t));" atamak ve son olarak "ngOnDestroy() {this.subscriberObj .unsubscribe();}" –

+0

sayesinde !!! Yukarıdaki tam kod çalışıyor! –