首页 > 解决方案 > 对 ngrx 效果的操作类型不匹配

问题描述

我用这 3 个动作创建了一个动作文件:

export const showLoading = createAction(`[application] Show warning notification`);
export const hideLoading = createAction(`[application] Show error notification`);
export const showHttpResponseError = createAction(`[application] Show success notification`, props<{ error: HttpErrorResponse, nextAction: Action }>());

export type Actions = ReturnType<
typeof showLoading |
typeof hideLoading |
typeof showHttpResponseError
>;

然后我创建了一个这样的效果文件:

@Injectable()
export class ApplicationEffects
{
    constructor(private actions$: Actions, private dialogsService: DialogsService, public notificationsService: NotificationService, private router: Router) { }

    @Effect() public erroHandler$ = this.actions$
        .pipe(
            ofType(ApplicationActions.showHttpResponseError.type),
            switchMap(action => {
                    const emptyAction = { type: 'noop' };
                    const error = HttpErrorHandler.handle(action.error);

                    if (error.redirectTo != null) {
                        this.router.navigate([error.redirectTo]);
                        return of(emptyAction);
                    }

                    if (action.error.status === 400) {
                        this.notificationsService.notifyWarning('AVISO', error.messages);
                    }
                    else {
                        this.dialogsService.errorDialog('ERRO', error.messages[0]);
                    }

                    return action.nextAction ? of(action.nextAction) : of(emptyAction);
                },
            ));
}

但由于某种原因,VS Code intellisense 无法识别 中的动作类型switchMap,它说它是类型never

在此处输入图像描述

我错过了什么吗?或者我怎么能强制它的类型,因为动作是使用 ngrx 动作创建者创建的,我没有明确的类型。

标签: angulartypescriptvisual-studio-codengrxngrx-effects

解决方案


为了完整起见,有多种方法:

1)ofType运营商类型

ofType<AddAction>(CounterActions.AddAction)

2)输入注入的动作,就像你已经回答的那样(从 NgRx 7 开始)

constructor(private actions$: Actions<CounterActions.Actions>

3)createEffect结合使用createAction(从 NgRx 8 开始)

foo$ = createEffect(() => this.actions$.pipe(
    ofType(addAction),
    ...
);

推荐阅读