禁用订阅

时间:2020-06-29 03:24:16

标签: angular

我需要关闭订阅才能挂起。我可以正确断开订阅吗?如果转到另一个页面,则该请求将起作用,尽管该流程组件实际上必须处于非活动状态。

  ngUnsubscribe = new Subject<void>();

  ngOnInit() {
    setInterval(() => {
      this.load();
    }, 1000);
  }

  load() {
    this._card.get().pipe(takeUntil(this.ngUnsubscribe)).subscribe(card => {
      this.card = card;
    })
    
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

1 个答案:

答案 0 :(得分:2)

下面的代码将取消订阅,也应停止计时器。希望这会有所帮助。

import { Subscription } from 'rxjs/Subscription';

ngUnsubscribe: Subscription;
interval;

ngOnInit() {
this.interval = setInterval(() => {
  this.load();
 }, 1000);
}

load() {
    this.ngUnsubscribe = this._card.get().subscribe(card => {
      this.card = card;
    });
}

ngOnDestroy() {
 clearInterval(this.interval);
 this.ngUnsubscribe.unsubscribe();
}