首页 > 解决方案 > RxJS:禁止在效果和史诗中使用不安全的 catch 并请求嵌套

问题描述

我有一个效果,它的主要思想是用 API 做一些“魔术”,主要问题:首先我需要发出一个请求,成功后我需要发出第二个请求。一切都很好,直到我将代码更改为这个(看起来更具可读性):

@Effect()
    myEffect$ = this.actions$.pipe(
        ofType(actionTypes.SomeDataAction),
        withLatestFrom(this.store.select(selectTheAwesome)),
        concatMap(([action, awesomeData]) =>
            forkJoin([
                of(awesomeData),
                this.myService.makeFirstMagic(
                    action.payload.someDataId
                )
            ])
        ),
        concatMap(data => {
            const [awesomeData, magicFirst] = data;

            return this.myService.makeSecondMagic(awesomeData.awesomeDataId, magicFirst.newId).pipe(
                mergeMap(response => {
                    return [new SomeDataActionSuccess(), new SomeAnotherDataAction([response])];
                })
            );
        }),
        catchError((error) => of(new SomeDataActionError({ error })))
    );

但结果 ts-lint 失败了RxJS: Unsafe catch usage in effects and epics is forbidden. 我做错了什么?为什么它曾经使用这样的代码工作(通过 linting)?

@Effect()
    myEffect$ = this.actions$.pipe(
        ofType(actionTypes.SomeDataAction),
        withLatestFrom(this.store.select(selectTheAwesome)),
        mergeMap(([action, awesomeData]) => {
            return this.myService.makeFirstMagic(action.payload.someDataId).pipe(
                mergeMap(magicFirst => {
                    return this.myService.makeSecondMagic(awesomeData.awesomeDataId, magicFirst.newId).pipe(
                        mergeMap(response => {
                            return [new SomeDataActionSuccess(), new SomeAnotherDataAction([response])];
                        })
                    );
                })
            );
        }),
        catchError(error => of(new SomeDataActionError({ error })))
    );

标签: javascripttypescriptrxjsngrxtslint

解决方案


您必须使用catchError每种服务方法,例如

this.myService.makeSecondMagic(awesomeData.awesomeDataId, magicFirst.newId).pipe(
                mergeMap(response => {
                    return [new SomeDataActionSuccess(), new SomeAnotherDataAction([response])];
                }),
                catchError(....)
            );


推荐阅读