angular - 使用 NGRX 的 RXJS 链订阅反模式
问题描述
我有以下代码,它正在工作,但我读过链接订阅是一种反模式。在调用需要用户 authtoken 的 API 之前,我需要确保用户的登录状态为 true。
在 RXJS 中处理这个问题的正确方法是什么?
const subscrAuth = this.store
.pipe(select(isLoggedIn))
.subscribe(isLoggedIn => {
console.log(isLoggedIn);
if (isLoggedIn) {
const subscrLoaded = this.store
.pipe(select(hasCarriersLoaded))
.subscribe(hasCarrierLoaded => {
if (!hasCarrierLoaded) {
this.store.dispatch(new CarriersPageRequested());
}
});
}
});
this.unsubscribe.push(subscrAuth);
解决方案
像这样的东西?
const subscrAuth = this.store
.pipe(
select(isLoggedIn),
switchMap(isLoggedIn => {
this.store.pipe(
select(hasCarriersLoaded),
tap(hasCarriersLoaded => {
this.store.dispatch(new CarriersPageRequested());
})
)
})
).subscribe();
this.unsubscribe.push(subscrAuth);
我还建议使用 ngOnDestroy 函数来管理您的订阅,如下所示,
onDestroy$: Subject<null> = new Subject();
ngOnDestroy() {
this.onDestroy$.next();
}
this.store
.pipe(
takeUntil(this.onDestroy$),
select(isLoggedIn),
switchMap(isLoggedIn => {
this.store.pipe(
select(hasCarriersLoaded),
tap(hasCarriersLoaded => {
this.store.dispatch(new CarriersPageRequested());
})
)
})
).subscribe();
或者,如果您只想打一个电话,您也可以像这样修改管道
this.store
.pipe(
take(1),
select(isLoggedIn),
switchMap(isLoggedIn => {
this.store.pipe(
select(hasCarriersLoaded),
tap(hasCarriersLoaded => {
this.store.dispatch(new CarriersPageRequested());
})
)
})
).subscribe();
推荐阅读
- arduino - 导入 PN532Interface.h 时出现“没有此类文件错误”
- javascript - 使用输入中的文本更新 div
- python-3.x - 如何更改使用 xrange 在 python 3 中运行的代码?
- python - 将我的数据框的行从个人转换为按组计数以执行树形图
- python - 让 Optimizer 根据容量和净负载切换电力存储
- javascript - 无法使用 Excel JavaScript API 设置 NumberFormat
- scala - 从 Spark Scala 中的旧数据框中获取列名
- c# - GUIText 替换?
- caching - Hazelcast 在所有节点上持久化和加载数据
- php - Symfony 内核没有从 Symlinked 作曲家包中找到命名空间