加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 如何取消订阅/停止Observable?

发布时间:2020-12-17 06:51:54 所属栏目:安全 来源:网络整理
导读:我使用以下代码作为计时器: export class TimerService { private ticks: number = 0; private seconds: number = 0; private timer; constructor(seconds: number) { this.seconds = seconds; this.timer = Observable.timer(2000,1000); this.timer.subsc
我使用以下代码作为计时器:

export class TimerService {
  private ticks: number = 0;
  private seconds: number = 0;
  private timer;

  constructor(seconds: number) {
    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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读