angular - NgRx 效果 mergeMap 方法

标签 angular typescript rxjs 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 }))
            )
        )
    );

最佳答案

有一个很好的指南here好的和坏的做法。

考虑你的第二个例子。如果您想在第二张 map 中添加另一个 map 怎么办?

   pollingStarted$ = createEffect(() =>
        this.actions$.pipe(
            ofType(pollingStarted),
            mergeMap(({ instances }) =>
                instances.map(instance => performRequest({ 
                    instance.map(() => { // And another map})
                }))
            )
        )
    );

这将很快使您的代码不可读。错误处理呢?

在您的第一个示例中,您可以只添加一个适用于所有 map 的 catchError。在第二种情况下,您需要为您在那里拥有的每张 map 执行错误处理。

    // VERY BAD: nesting subscribes is ugly and takes away
    // the control over a stream


这同样适用于 map 和任何其他应该通过管道传输的操作符。管道运算符相当于 linux 管道 |,被认为是最佳实践。它提供了更清晰的代码。

仅对其中几个可能没有意义,但是当它嵌套在多个级别时,它变得非常讨厌并且代码变得不可读。

我最近进行了一次重构,使状态 2 看起来像一个大项目中的状态,以便我可以更好地管理代码。

关于angular - NgRx 效果 mergeMap 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58997509/

相关文章:

angular - 如何从服务中调用组件方法? ( Angular 2)

javascript - Angular 中连续异步函数的问题

asp.net-mvc-5 - 如何让 angular2 在 Visual Studio 2015 中使用 TypeScript 工作?

javascript - rxjs simple do http get 什么也不做

javascript - RxJS 在 Ajax 错误后继续监听

angular - 如何处理 "EmptyError: no elements in sequence"?

javascript - 找不到管道 : Angular 5 custom pipe

json - 在 *ngfor 上使用对象

angular - 未找到 '{Module Name}' 的 NgModule 元数据错误

javascript - 事件存储未知错误 : Could not recognize BadRequest