angular - 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 生命周期钩子中加入订阅和取消订阅。请建议如何解决这个问题。提前致谢。
解决方案
问题是在第一次离开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();
}
}
推荐阅读
- cmd - Windows机器上的git-lab-runner中的命令不起作用
- unity3d - 当 AppendStructuredBuffer 在计算着色器中溢出时会发生什么?
- sql - 无法合并 2 个表
- python-3.x - \n 在 Python 3 中的混淆
- python - 如何将 Pandas 列切片转置并插入行切片?
- xml - 如何以与 androidstudio 中相同的大小显示我的按钮和图像视图?
- swift - 如何更改 CAShapeLayer 内的区域?
- aws-lambda - 如何在持久服务和同步无服务器功能之间定义 Pact 合约?
- php - ajax 不会去控制器并且数据不会更新
- json - 使用 VB.net 和 Newtonsoft.Json 解析复杂的 Json 数据