【问题标题】:subscription.subscribe and unsubscribe is not a functionsubscription.subscribe 和 unsubscribe 不是一个函数
【发布时间】: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


【解决方案1】:

为了使您可以稍后再订阅但也停止侦听 observable,您可以在 observable 上使用另一个名为 takeWhile 的函数。您将返回布尔值 (() =&gt; { 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;
});

还要确保在您的 toggleStopwatch() 函数中删除 .unsubscribe() 调用!

已更新以反映问题的变化,请参阅原始答案的修订版。

【讨论】:

    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 2018-06-22
    • 2017-11-26
    • 2020-08-09
    • 2019-02-21
    • 1970-01-01
    • 2014-01-31
    • 2016-07-08
    相关资源
    最近更新 更多