【发布时间】:2018-03-10 15:05:23
【问题描述】:
我正在尝试取消订阅 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
【问题讨论】:
-
发布准确完整的异常堆栈跟踪。但是订阅,您选择键入为 any,从而消除了 TypeScript 将为您执行的所有类型检查,它不是订阅。这是一个可观察的。而且 Observable 中没有 unsubscribe 方法。不要使用任何。为变量指定适当的类型,TypeScript 会在构建时为您发现编程错误。这就是 TypeScript 的重点。
-
我记不太清了,但是 Observable.interval 和 Angular 有一些奇怪的地方需要使用
import { IntervalObservable } from 'rxjs/observable/IntervalObservable'; -
@JBNizet 堆栈跟踪已添加,ty for the typescript Tips,你知道我怎样才能让这些可观察的东西能够被观察到吗?
-
@rjustin ty,我尝试了您的解决方案,但没有成功
-
我会先使用推荐的导入:
import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/interval';然后决定你想在 this.subscription 中存储什么。要么是 Observable,你应该输入 Observable,重命名它,然后修复代码,或者它是 Subscription,你应该输入 Subscription,然后修复代码。
标签: typescript rxjs angular2-observables