属性 'payload' 类型“TypedAction”上不存在。我如何从 ngrx 效果访问 action.payload?

Property 'payload' does not exist on type 'TypedAction. How i can access the action.payload from a ngrx effect?

我正在学习如何在 Angular 中使用 ngrx 效果。我正在关注 ngrx 文档并尝试实现我的第一个效果:

在我的组件中,我创建了一个 dispatch() 来加载用户列表:

public ngOnInit(): void {
  this.store.dispatch({ type: '[User Page] Load Users' });
}

我创建这个效果是为了听我的动作并从我的 api:

拨打电话
loadUsers$ = createEffect(() =>
  this.actions$.pipe(
    ofType('[User Page] Load Users'),
    mergeMap(() =>
      this.usuarioService.read().pipe(
        map((users) => ({
          type: '[Users API] Users Loaded Success',
          payload: users
        })),
        catchError(() => EMPTY)
      )
    )
  )
);

这是我的减速器:

export const initialState = {
  users: []
};

const _userReducer = createReducer(
  initialState,
  on(setUserList, (state, action) => ({ ...state, users: action.payload }))
);

这是我的 setUserList 操作:

export const setUserList = createAction('[Users API] Users Loaded Success');

一切正常,但当我尝试访问 action.payload:

时,我在 vscode 中收到警告

Property 'payload' does not exist on type 'TypedAction<"[Users API] Users Loaded Success"> & { type: "[Users API] Users Loaded Success"; }'.ts(2339)

我该如何解决这个警告?

我修复了这个警告,创建了一个具有负载 属性:

的接口
import { Actions } from '@ngrx/effects';

export interface IActionWithPayload extends Actions {
  type: string;
  payload?: any;
}

所以我用这个界面输入了我的动作,错误消失了:

const _userReducer = createReducer(
  initialState,
  on(setUserList, (state, action: IActionWithPayload) => ({
    ...state,
    users: action.payload
  }))
);

您需要将 users 定义为类型为 User[] 的操作的 属性,因此:

import { createAction, props } from '@ngrx/store';

export interface User {
    id: number;
    name: string;
}

export const setUserList = createAction('[Users API] Users Loaded Success', props<{ users: User[] }>());

有关此内容的更多信息 here

那么在你的效果中,我相信你可以做到:

map((users) => ({
    type: '[Users API] Users Loaded Success',
    users
})),