首页 > 解决方案 > 禁用订阅

问题描述

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

  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();
  }

标签: angular

解决方案


下面的代码将取消订阅并且还应该停止计时器。希望这可以帮助。

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();
}

推荐阅读