我有两个效果相同的实现,两者都能工作。我很难理解两者之间的不同之处,而这一点更“正确”。
请在下面找到它们:
选项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 }))
)
)
);发布于 2019-11-29 11:36:35
第一种方法似乎不应奏效:
pollingStarted$ = createEffect(() =>
this.actions$.pipe(
ofType(pollingStarted),
mergeMap(action => action.instances),
map(instance => performRequest({ instance }))
)
);在本例中,mergeMap为数组平面图,map为每个发出的值返回一个观察者。最后,您将得到一个可观察的可观测值(Observable<Observable<your type>>)。您需要使用一个高阶可观测值而不是map来使其工作。
第二个选择是正确的:
pollingStarted$ = createEffect(() =>
this.actions$.pipe(
ofType(pollingStarted),
mergeMap(({ instances }) =>
instances.map(instance => performRequest({ instance }))
)
)
);在本例中,mergeMap将由instances.map生成的一系列可观测数据合并到一个可观察到的对象中。使用这种方法的好处是,您可以控制可观察性,可以将catchError应用于每个performRequest,或者在mergeMap之后将其应用于更高级别,以便对所有performRequest调用进行单一错误处理。
发布于 2019-11-22 16:04:20
有一个非常好的指南这里的好和坏的做法。
考虑第二个例子。如果你想在你的第二张地图中添加阳极映射呢?
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看起来像一个大项目中的状态,这样我就可以更好地管理代码。
https://stackoverflow.com/questions/58997509
复制相似问题