尝试制作一个简单的计时器,并需要在某些if条件下破坏它。但是总是有一个错误的EXCEPTION: timer.unsubscribe is not a function。
我做错了什么?
let timer:any = Observable.timer(0,1000);
timer.subscribe(data => {
console.log(this.itemsRatedList);
if(data == 5) timer.unsubscribe();
});发布于 2016-10-21 16:14:12
它应该是:
let timer:any = Observable.timer(0,1000);
let subscription = timer.subscribe(data => {
console.log(this.itemsRatedList);
if(data == 5)
subscription.unsubscribe();
});你不能unsubscribe一个Observable,只有一个Subscription。
发布于 2017-07-28 06:51:42
一个更清晰和简单的例子就是这个例子,我认为这个例子更清楚。
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
复制相似问题