Reducer 在 ngrx 中抛出“错误对象 null 不可迭代”
2020-02-18
506
我有一个名为
doctors.list.component.ts
的组件,它呈现医生列表。我使用 @ngrx/effect 从 API 获取此医生。我想使用 ng-modal 向此列表添加新医生。流程是当用户从 ng-modal 选择医生时,必须将其添加到现有的医生列表中。为此,我编写了新的操作和 Reducer。这个 Reducer 抛出
error object null is not iterable
这是我的 doctorlist.action.ts
import { createAction, props } from '@ngrx/store';
import { Doctors } from 'src/app/admin/models/doctorProfileAdmin'
export const loadDoctors = createAction('[Doctors] Doctors List Request', props<{ hospitalId: string }>())
export const loadDoctorsSuccess = createAction('[Doctors] Doctors List Load Success', props<{ doctors: Doctors[] }>())
export const loadDoctorsFail = createAction('[Doctors] Doctors List Load Fail', props<{ errorMessage: string }>())
export const addExistingDoctorToList = createAction('[Doctors] Doctors List Load Success', props<{ doctor: Doctors }>())
在我的 doctor.list.reducer.ts 中
import { createReducer, on, Action } from '@ngrx/store';
import { DoctorListState } from '../state/doctorList.state';
import { loadDoctors, loadDoctorsSuccess, loadDoctorsFail,addExistingDoctorToList } from '../actions/doctorList.actions';
const initialState: DoctorListState = {
doctors:null,
error: null,
isLoading: false
};
const doctorListReducer = createReducer(initialState,
on(loadDoctors, (state) => {
return { ...state, isLoading: true };
}),
on(loadDoctorsSuccess, (state, { doctors }) => {
return { ...state, doctors: doctors, isLoading: false };
}),
on(loadDoctorsFail, ((state, { errorMessage }) => {
return { ...state, errorMes: errorMessage, isLoading: false };
})),
on(addExistingDoctorToList, (state, { doctor }) => {
return { ...state, doctors:[...state.doctors,doctor], isLoading: false };
}),
);
export function reducer(state: DoctorListState | undefined, action: Action) {
return doctorListReducer(state, action);
}
我也将 initialState 医生属性更改为空数组。然后不会出现此错误,但我的医生列表也不会显示在组件中
这是我在组件初始化时将医生获取到我的
doctors.list.component.ts
的方法。
this.store.pipe(select(selectDoctorsList)).pipe(skip(1)).subscribe(payload => {
this.doctorList = payload;
})
添加新的 docotr 事件点击功能
addNewDoctor(){
this.store.dispatch(addExistingDoctorToList({doctor:selectedDoctor}))
}
我不明白我在这里做错了什么。
1个回答
查看动作定义
export const loadDoctorsSuccess = createAction('[Doctors] Doctors List Load Success', props<{ doctors: Doctors[] }>())
export const addExistingDoctorToList = createAction('[Doctors] Doctors List Load Success', props<{ doctor: Doctors }>())
这两个动作具有相同的字符串,用作action.type。它们应该是唯一的,因此ngrx会将它们视为不同的动作。
Andrei
2020-02-18