简体   繁体   English

unsubscribe 不是 observable 中的 function

[英]unsubscribe is not a function in an observable

I have a function that should be a base for a stopwatch.我有一个 function 应该是秒表的底座。 It returns some values for different methods.它为不同的方法返回一些值。 I use a subscribtion for an observable there, and I want to unsubscribe from it when my timer is stopped, but it returns an error "TypeError: this.customIntervalObservable.unsubscribe is not a function"我在那里为可观察对象使用订阅,当我的计时器停止时我想取消订阅它,但它返回错误“TypeError:this.customIntervalObservable.unsubscribe is not a function”

What might be the problem and how can I fix it?可能是什么问题,我该如何解决?

My observable code:我的可观察代码:

      customIntervalObservable = Observable.create((observer) => {
    let count = 0;
    setInterval(() => {
      observer.next(count);
      count = count + this.deg;
    }, 1000);
  });

My method code is:我的方法代码是:

  stopWatch(isSubscribed) {
    if (isSubscribed) {
      this.customIntervalObservable.subscribe((sec) => {
        this.ss = sec;
        this.getSeconds(this.ss);
        if (this.ss / (60 * this.deg) === 1) {
          this.ss = 0;
          this.mm = this.mm + 6;
          this.getMinutes(this.mm);

          if (this.mm / (60 * this.deg) === 1) {
            this.mm = 0;
            this.hh = this.hh + 6;
            this.getHours(this.hh);
          }
        }
      });
    } else {
      this.customIntervalObservable.unsubscribe();
    }
  }

You can't unsubscribe an Observable , just a Subscription .你不能取消订阅Observable ,只能取消Subscription

First, get a reference to that subscription:首先,获取对该订阅的引用:

stopWatch(isSubscribed) {
    if (isSubscribed) {
      this.subscription = this.customIntervalObservable.subscribe(...)
    ...
    }
}

Then, in the else-path, you can write:然后,在 else-path 中,您可以编写:

else {
    this.subscription.unsubscribe();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM