gpt4 book ai didi

javascript - ngrx效果中api调用后获取数据

转载 作者:行者123 更新时间:2023-12-02 23:16:27 24 4
gpt4 key购买 nike

我正在使用 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....
}
]
}
};

和 reducer

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$ 没有获得更新?

最佳答案

 case ESchedulesActions.GetSchedulesByDateSuccess: {
return {
...state
};
}

在这里,您只是返回状态的一个副本。您应该做的是使用 action 有效负载来更新状态(我不完全知道您的状态是如何构造的,但这提供了一个想法):

 case ESchedulesActions.GetSchedulesByDateSuccess: {
return {
...state,
schedulings: action.payload
};
}

关于javascript - ngrx效果中api调用后获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57146196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com