Ionic 4 的 NGRX 多重订阅问题

NGRX multiple subscription issue with Ionic 4

我在 ngrx 中使用 ionic 4。我在页面 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.Both 页上,页面会收到通知。我知道在 ionic 中,前一页保留在堆栈中,因此 onDestroy() 永远不会在向前导航时被调用,这就是为什么我在 ionic 生命周期挂钩中加入了订阅和取消订阅。 请建议如何解决这个问题。提前致谢。

问题是第一次离开this.ngUnsubscribe完成后,意味着下次调用ionViewWillLeavethis.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();
  }
}