angular - NgRx 效果 mergeMap 方法
问题描述
我有两个相同效果的实现,并且都有效。我很难理解两者之间的区别,哪个更“正确”。
请在下面找到它们:
选项 1. IDE 无法确定instance
最后一个map
.
pollingStarted$ = createEffect(() =>
this.actions$.pipe(
ofType(pollingStarted),
mergeMap(action => action.instances),
map(instance => performRequest({ instance }))
)
);
选项 2。所有类型都有效且有意义。这对我来说更正确,但我想弄清楚并理解这些差异。
pollingStarted$ = createEffect(() =>
this.actions$.pipe(
ofType(pollingStarted),
mergeMap(({ instances }) =>
instances.map(instance => performRequest({ instance }))
)
)
);
解决方案
这里有一个非常好的指南,介绍了好的和坏的做法。
考虑你的第二个例子。如果您想在第二张地图中添加另一张地图怎么办?
pollingStarted$ = createEffect(() =>
this.actions$.pipe(
ofType(pollingStarted),
mergeMap(({ instances }) =>
instances.map(instance => performRequest({
instance.map(() => { // And another map})
}))
)
)
);
这很快就会使您的代码不可读。错误处理呢?
在您的第一个示例中,您可以只添加一个适用于所有地图的 catchError。在第二种情况下,您需要为您在那里拥有的每张地图做一个错误处理。
// VERY BAD: nesting subscribes is ugly and takes away // the control over a stream
这同样适用于地图和任何其他应该通过管道传输的运算符。管道运算符相当于 linux 管道 |,被认为是最佳实践。它提供了更简洁的代码。
对于其中的几个可能没有意义,但是当它嵌套在多个级别时,它会变得非常讨厌并且代码变得不可读。
我最近进行了重构,使状态 2 看起来像一个大型项目中的状态,以便我可以更好地管理代码。
推荐阅读
- arrays - MIPS 1D 整数数组,在索引处插入
- c - 以 -1 作为退出整数的 n 个数字的总和和平均值
- java - 组合:容器可以在没有其包含的对象之一的情况下存在吗?爪哇
- python - 在列表 2 中垂直添加具有相同标题的 list1
- javascript - 错误未捕获类型错误:无法读取未定义的属性“0”。艾克灯箱
- c# - 将 json 反序列化为 FHIR 约会实例时遇到问题
- tensorflow - 为多系列建模 LSTM 时的问题
- sql-server - Powershell - SQL 数据库显示用户权限
- c# - Emug cv C# 最小阈值截断
- ios - 应用重启后仅由 EnvironmentObject 更新的视图