问题描述
我正在使用 ngrx 并且有一个场景,我需要同时调度 2 个动作.我的状态具有用于更新和更新的属性,如下所示.
I'm using ngrx and have a scenerio where I need to dispatch 2 actions at the same time. My state has properties for updating and updated and looks like below.
//from reducer
const defaultCardState: CardState = {
ids: [],
entities: {},
loaded: false,
loading: false,
adding: false,
added: false,
updating: false,
updated: false,
deleting: false,
deleted: false
};
这些是我从我的组件分派的动作
These are the actions I'm dispatching from my component
this.store.dispatch(fromCard.updateCard({id: id1, changes: {name: name1}}))
this.store.dispatch(fromCard.updateCard({id: id2, changes: {name: name2}}))
下面是我的动作、减速器和效果
Below are my action, reducer and effect
//Update Card Actions
export const updateCard = createAction('[Cards] Update Card', props<{id: string, changes: any}>())
export const updateCardSuccess = createAction('[Cards] Update Card Success', props<{changes: any}>());
export const updateCardFail = createAction('[Cards] Update Card Fail')
//Reducer
on(fromCards.updateCard, (state) => ({...state, updating: true, updated: false})),
on(fromCards.updateCardSuccess, (state, action: any) => ({...cardAdapter.updateOne(action.changes, state), updated: true, updating: false})),
on(fromCards.updateCardFail, (state, action: any) => fromCards.updateCardFail),
//Update Card Effect
updateCard$: Observable<Action> = createEffect(() => this.actions$.pipe(
ofType(fromCardActions.updateCard),
map((action: any) => { return {id: action.id, changes: action.changes}}),
switchMap((action: any) => this.cardService.updateCard(action).pipe(
map((res) => (fromCardActions.updateCardSuccess({changes: action }))),
catchError(() => of(fromCardActions.updateCardFail))
))
))
一个接一个地分派这些动作以便更新和更新的字段不冲突的最佳方法是什么?如果我只运行其中之一,它就可以工作,但如果我像上图一样将它们一起分派,则只有一个完成.我看到两个操作都被调度,但只有一个成功操作被调度.
What is the best way to dispatch these actions one after the other so the updating and updated fields don't conflict? If I run just one of these it works but if I dispatch them both together like shown above, only one completes. I see that both actions get dispatched but only one success action gets dispatched.
推荐答案
你可以在你的 effect 中调度多个 action,我建议你只在 effect 中这样做
You can dispatch multiple action in your effect and I would recommend you do that only in the effect
考虑下面的例子
@Effect()
dispatchMultiAction$: Observable<Action> = this.actions$.pipe(
ofType<SomeAction.Dispatch>(someActions.Dispatch),
switchMap(_ =>
of(
new someActions.InitData(),
new someActions.GetData(),
new someActions.LoadData()
)
)
);
这篇关于如何同时调度多个 ngrx 动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!