2016-09-18 24 views
7

मैं टाइमर बनाने की कोशिश कर रहा हूं, जो हर 5 सेकंड में जीईटी अनुरोध भेज देगा, मैं इसे करने में कामयाब हूं, लेकिन मुझे लगता है कि अगर मैं टाइमर अभी भी चल रहा हूं, तो अलग-अलग पेज (रूटिंग) पर जाता हूं, इसलिए मैं ngOnDestroy जोड़ने की कोशिश की है, लेकिन मैं "सदस्यता समाप्त" विधिकोणीय 2: टाइमर बनाएं और नष्ट करें

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

 
    } 
 
} 
 

 

मैं angular2 RC7 उपयोग कर रहा हूँ नहीं है, "rxjs": "5.0.0-beta.12"

उत्तर

19

एक अवलोकन योग्य रिटर्न की सदस्यता एक सदस्यता वस्तु

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

नमस्ते मैं एक समस्या है, जब मैं एक और पेज यह बंद हो जाता है पर जाएँ लेकिन जब मैं इस पृष्ठ पर वापस आ गया तो 2 टाइमर शुरू होता है। –

1

, बस आप

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

सदस्यता समाप्त करने के कहाँ myObservable वस्तु subscribe() द्वारा दिया है की जरूरत है।

refrence: angular2 - Best way to terminate a observable interval when path changes

+1

क्या आपका मतलब है: this.timer.uns सदस्यता लें(); - क्योंकि मुझे सदस्यता समाप्त नहीं हो रही है(); इस.timer टाइप करते समय। –

+1

एक चर "निजी ग्राहक ओबीजे: सदस्यता;" बनाएं और उसके बाद आवंटित यह "this.subscriberObj = this.timer.subscribe (टी => this.tickerFunc (टी));" और अंत में "ngOnDestroy() {this.subscriberObj .unsubscribe();}" –

+0

धन्यवाद !!! आपका उपरोक्त पूर्ण कोड बहुत अच्छा काम कर रहा है !! –

संबंधित मुद्दे