subscription.subscribe 并且取消订阅不是函数

subscription.subscribe and unsubscribe is not a function

我正在尝试取消订阅一个 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

为了让您可以稍后订阅但也停止监听可观察对象,您可以在可观察对象上使用一个名为 takeWhile 的不同函数。您将 returns 布尔值 (() => { return true || false; }) 的谓词传递给 takeWhile 函数,如果它 returns 为真,则它会继续侦听。您的 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() 调用!

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