2017-07-21 8 views
1

Ich verwende den folgenden Code für Timer:Abmelden/stoppen Observable?

export class TimerService { 
    private ticks: number = 0; 
    private seconds: number = 0; 
    private timer; 

    constructor(seconds: number) { 
    this.seconds = seconds; 
    this.timer = Observable.timer(2000, 1000); 
    this.timer.subscribe(t => { 
     this.ticks = t; 
     this.disactivate(); 
    }); 
    } 

    private disactivate() { 
    if (this.ticks === this.seconds) { 
     this.timer.dispose(); 
    } 
    } 
} 

Wenn ich versuche, Timer in Linie zu stoppen:

this.timer.dispose(); // this.timer.unsubscribe(); 

Es ist nicht für mich

+0

was wollen Sie damit archivieren? –

+0

Ich muss den Timer stoppen und die letzte Timerzeit in Sekunden fixieren. – OPV

Antwort

5

Die subscribe Methode gibt ein Subscription Objekt funktioniert , die Sie später verwenden können, um den Stream zu stoppen, der in der Observablen enthalten ist, für die Sie sich angemeldet haben.

import { ISubscription } from 'rxjs/Subscription': 
import { TimerObservable } from 'rxjs/observable/TimerObservable'; 

export class TimerService { 
    private ticks = 0; 
    private timer$: TimerObservable; 
    private $timer : ISubscription; 

    constructor(private seconds = 0) { 
    this.timer$ = TimerObservable.create(2000, 1000);//or you can use the constructor method 
    this.$timer = this.timer.subscribe(t => { 
     this.ticks = t; 
     this.disactivate(); 
    }); 
    } 

    private disactivate() { 
    if (this.ticks >= this.seconds) { 
     this.$timer.unsubscribe(); 
    } 
    } 
} 

Es ist wichtig zu bemerken, dass unsubscribe existieren in rxjs (Version 5 und höher), vor, dass in rx (Version niedriger als 5, ein anderes Paket) die Methode aufgerufen wurde dispose

+0

Können Sie die Lösung kommentieren? Was ist 'this. $ Timer'? – OPV

+0

nur eine Namenskonvention für Abonnements und 'Timer $' für Observables –