首页 > 解决方案 > Ionic 4 的 NGRX 多订阅问题

问题描述

我正在使用 ionic 4 和 ngrx。我在页面 A 和页面 b 上都有一个用户选择器。

export class ComponentA implements OnInit, OnDestroy {

  private readonly ngUnsubscribe: Subject<void> = new Subject<void>();
  user:any;
  constructor(
    private readonly store: Store<AppState>,
  ) { }

ngOnInit(){}

  ionViewWillEnter(): void {
    this.store.select(getUserState)
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe((user) => {
        this.user = user;
      });
  }

  ionViewWillLeave(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
    getUserState.release();
  }  

页面 b 上的相同订阅,当我从页面 a 移动到 b 时取消订阅有效,但是当我从 b 移动到 a,然后从 a 移动到 b .. 页面 a 上的订阅不会取消订阅。如果您返回 5 次 5 订阅仍留在页面 a。两个页面都会收到通知。我知道在 ionic 上一页仍然在堆栈中,所以 onDestroy() 永远不会在前向导航中被调用,这就是为什么我在 ionic 生命周期钩子中加入订阅和取消订阅。请建议如何解决这个问题。提前致谢。

标签: angularionic-frameworkionic4ngrx

解决方案


问题是在第一次离开this.ngUnsubscribe完成后,这意味着下一次ionViewWillLeave被调用的时间this.ngUnsubscribe已经完成并且不会发出终止信号。

您可以将完整部分移动到 ngOnDestroy 以保持流处于活动状态,直到真正处置。

export class ComponentA implements OnInit, OnDestroy {

  private readonly ngUnsubscribe: Subject<void> = new Subject<void>();
  user:any;
  constructor(
    private readonly store: Store<AppState>,
  ) { }

  ngOnInit(){}

  ionViewWillEnter(): void {
    this.store.select(getUserState)
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe((user) => {
        this.user = user;
      });
  }

  ionViewWillLeave(): void {
    this.ngUnsubscribe.next();
    getUserState.release();
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.complete();
  }
}

推荐阅读