Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angular – 如何取消订阅/停止Observable?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下代码作为计时器:

export class Timerservice {
  private ticks: @R_675_10793@er = 0;
  private seconds: @R_675_10793@er = 0;
  private timer;

  constructor(seconds: @R_675_10793@er) {
    this.seconds = seconds;
    this.timer = Observable.timer(2000,1000);
    this.timer.subscribe(t => {
      this.ticks = t;
      this.disactivate();
    });
  }

  private disactivate() {
    if (this.ticks === this.seconds) {
      this.timer.dispose();
    }
  }
}

当我尝试停止计时器时:

this.timer.dispose(); // this.timer.unsubscribe();

它对我不起作用

解决方法

subscribe方法返回一个Subscription对象,稍后您可以使用该对象来停止侦听您订阅的observable所包含的流.

import { ISubscription } from 'rxjs/Subscription':
import { TimerObservable } from 'rxjs/observable/TimerObservable';

export class Timerservice {
  private ticks = 0;
  private timer$: TimerObservable;
  private $timer : ISubscription;

  constructor(private seconds = 0) {
    this.timer$= TimerObservable.create(2000,1000);//or you can use the constructor method
    this.$timer = this.timer.subscribe(t => {
      this.ticks = t;
      this.disactivate();
    });
  }

  private disactivate() {
    if (this.ticks >= this.seconds) {
      this.$timer.unsubscribe();
    }
  }
}

重要的是要注意在rxjs(版本5及更高版本)中存在取消订阅,在此之前,在rx(版本低于5,不同的包)中,该方法称为dispose

大佬总结

以上是大佬教程为你收集整理的angular – 如何取消订阅/停止Observable?全部内容,希望文章能够帮你解决angular – 如何取消订阅/停止Observable?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。