我正在将离子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中放入了订阅和取消订阅的原因。请建议如何解决此问题。预先感谢。
问题是,在最先离开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();
}
}