我试图取消订阅Observable,我发现以下错误:
[ts] Property 'unsubscribe' does not exist on type 'Observable<number>'. Did you mean 'subscribe'?
此错误与代码有关:this.subscription.unsubscribe();
以下是整个文件:
import { Component, Input, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { IntervalObservable } from 'rxjs/observable/IntervalObservable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/observable/timer';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit {
public counting: boolean;
public triggerBtnText = 'GO!';
public subscription: Observable<number>;
@Input() count = 0;
constructor() {}
ngOnInit() {
this.counting = false;
}
toggleStopwatch(): any {
if (this.counting === false) {
this.counting = true;
this.triggerBtnText = 'STOP';
this.updateCount()
} else {
this.counting = false;
this.triggerBtnText = 'GO!';
this.subscription.unsubscribe();
}
}
updateCount() {
this.subscription = Observable.interval(1000);
this.subscription.subscribe(this.counter);
}
public counter(value) {
this.count = value;
console.log(value);
}
resetCount() {
this.count = 0;
}
}
这是一个可以测试的简单项目: https://bitbucket.org/wtkd/learning-rxjs/branch/moving-to-ng
答案 0 :(得分:1)
为了使它能够在以后订阅,但也停止监听observable,你可以在名为takeWhile的observable上使用不同的函数。您将一个返回布尔值(() => { return true || false; }
)的谓词传递给takeWhile函数,如果它返回true,则继续侦听。您的counting
变量将非常适用于此。有关工作示例,请参阅下面的代码:
建议代码:
this.subscription
.takeWhile(() => { // by calling takeWhile and passing in a predicate,
return this.counting; // you can have the subscription stop when the counting
}) // variable is false.
.subscribe((value) => {
this.counter = value;
});
另请务必删除.unsubscribe()
功能中的toggleStopwatch()
来电!
已更新以反映问题更改,请参阅原始答案的修订。