问题
Tried to make a simple timer and need to break it on some if
condition. But always got an error EXCEPTION: timer.unsubscribe is not a function
.
What am I doing wrong?
let timer:any = Observable.timer(0,1000);
timer.subscribe(data => {
console.log(this.itemsRatedList);
if(data == 5) timer.unsubscribe();
});
回答1:
It should be:
let timer:any = Observable.timer(0,1000);
let subscription = timer.subscribe(data => {
console.log(this.itemsRatedList);
if(data == 5)
subscription.unsubscribe();
});
You can't unsubscribe
an Observable
, only a Subscription
.
Plunker example
回答2:
A more clear and simple example is this try this example, I think is more clear.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'app-slider',
templateUrl: './slider.component.html',
styleUrls: ['./slider.component.css']
})
export class SliderComponent implements OnInit , AfterViewInit, OnDestroy {
Sliders: any;
timer: any;
subscription: any;
constructor() { }
ngOnInit() {
// after 3000 milliseconds the slider starts
// and every 4000 miliseconds the slider is gona loops
this.timer = Observable.timer(3000, 4000);
function showSlides() {
console.log('Test');
}
// This is the trick
this.subscription = this.timer.subscribe(showSlides);
}
// After the user live the page
ngOnDestroy() {
console.log('timer destroyd');
this.subscription.unsubscribe();
}
}
来源:https://stackoverflow.com/questions/40181169/timer-unsubscribe-is-not-a-function-angular2