我正在使用Ngrx Effect从API中获取数据,然后将这些数据添加到我的组件中。
在组件中
schedules$ = this.store.pipe(select(selectSchedulings));
ngOnInit() {
this.store.dispatch(new GetSchedules());
}
在动作中,我创建了两种类型
export class GetSchedules implements Action {
public readonly type = ESchedulesActions.GetSchedulesByDate;
}
export class GetSchedulesSuccess implements Action {
public readonly type = ESchedulesActions.GetSchedulesByDateSuccess;
constructor(public payload: ISchedules[]) {}
}
export type SchedulesAction = GetSchedules | GetSchedulesSuccess;
然后在我的效果中
export class SchedulingsEffects {
loadSchedulings$ = createEffect(() =>
this.actions$.pipe(
ofType(ESchedulesActions.GetSchedulesByDate),
mergeMap(() =>
this.apiCallsService.getSchedulings().pipe(
map(movies => ({ type: ESchedulesActions.GetSchedulesByDateSuccess, payload: movies })),
catchError(() => EMPTY)
)
)
)
);
constructor(private actions$: Actions, private apiCallsService: ApiCallsService) {}
}
我已将商店初始化为状态
import { ISchedules } from '../../shared/interfaces/scheduling.interface';
export interface ISchedulesState {
schedulings: ISchedules;
}
export const initialSchedulingState: ISchedulesState = {
schedulings: {
status: '',
data: [
{
..... Init values....
}
]
}
};
和减速器
export const SchedulingReducers = (
state = initialSchedulingState,
action: SchedulesAction
): ISchedulesState => {
switch (action.type) {
case ESchedulesActions.GetSchedulesByDate: {
return {
...state
};
}
case ESchedulesActions.GetSchedulesByDateSuccess: {
return {
...state
};
}
default:
return state;
}
};
运行我的应用程序时,我仅获得Init值。我在商店开发工具中看到触发了api并存储了数据,但是为什么schedules$
没有得到更新?
答案 0 :(得分:1)
case ESchedulesActions.GetSchedulesByDateSuccess: {
return {
...state
};
}
在这里,您只是在返回状态的对策。
您应该做的是使用action
有效负载来更新状态(我不完全知道您的状态如何构造,但这给出了一个主意):
case ESchedulesActions.GetSchedulesByDateSuccess: {
return {
...state,
schedulings: action.payload
};
}