[Ionic 4的NGRX多重订阅问题

问题描述 投票:0回答:1

我正在将离子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次,则页面a上仍有5个订阅。这两个页面都会收到通知。我知道在ionic的上一页中仍保留堆栈,因此onDestroy()永远不会在正向导航中被调用,这就是为什么我在ionic lifecyle hook中放入了订阅和取消订阅的原因。请建议如何解决此问题。预先感谢。

angular ionic-framework ionic4 ngrx
1个回答
0
投票

问题是,在最先离开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();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.