timer.unsubscribe不是函数Angular2
试图制作一个简单的计时器,并需要在某些timer.unsubscribe不是函数Angular2,angular,timer,angular2-observables,Angular,Timer,Angular2 Observables,试图制作一个简单的计时器,并需要在某些if条件下将其中断。但总是出现错误异常:timer.unsubscribe不是一个函数 我做错了什么 let timer:any = Observable.timer(0,1000); timer.subscribe(data => { console.log(this.itemsRatedList); if(data == 5) timer.unsubscribe();
if
条件下将其中断。但总是出现错误异常:timer.unsubscribe不是一个函数
我做错了什么
let timer:any = Observable.timer(0,1000);
timer.subscribe(data => {
console.log(this.itemsRatedList);
if(data == 5) timer.unsubscribe();
});
应该是:
let timer:any = Observable.timer(0,1000);
let subscription = timer.subscribe(data => {
console.log(this.itemsRatedList);
if(data == 5)
subscription.unsubscribe();
});
您不能取消订阅一个可观察的,只有订阅
一个更清楚、更简单的例子是这个试试这个例子,我觉得更清楚
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();
}
}
哇!太不体贴我了:)谢谢!