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

前端之家收集整理的这篇文章主要介绍了angular – 如何取消订阅/停止Observable?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下代码作为计时器:

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

猜你在找的Angularjs相关文章