如何同时调度多个 ngrx 动作

mat*_*c19 2 rxjs typescript redux ngrx angular

我正在使用 ngrx 并且有一个场景,我需要同时调度 2 个动作。我的状态具有用于更新和更新的属性,如下所示。

//from reducer
const defaultCardState: CardState = {
    ids: [],
    entities: {},
    loaded: false,
    loading: false,
    adding: false,
    added: false,
    updating: false,
    updated: false,
    deleting: false,
    deleted: false
};
Run Code Online (Sandbox Code Playgroud)

这些是我从我的组件分派的动作

this.store.dispatch(fromCard.updateCard({id: id1, changes: {name: name1}}))
this.store.dispatch(fromCard.updateCard({id: id2, changes: {name: name2}}))
Run Code Online (Sandbox Code Playgroud)

下面是我的动作,减速器和效果

//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))
    ))
))
Run Code Online (Sandbox Code Playgroud)

一个接一个地调度这些操作的最佳方法是什么,以便更新和更新的字段不冲突?如果我只运行其中之一,它就可以工作,但如果我像上图一样将它们一起分派,则只有一个完成。我看到两个动作都被调度,但只有一个成功动作被调度。

xan*_*key 6

类似于托尼的答案,但使用正确的运算符:

@Effect()
dispatchMultiAction$: Observable<Action> = this.actions$.pipe(
    ofType<SomeAction.Dispatch>(someActions.Dispatch),
    mergeMap(_ => [
            new someActions.InitData(),
            new someActions.GetData(),
            new someActions.LoadData()
        ])
    )
);
Run Code Online (Sandbox Code Playgroud)

  • Tony 使用“of([])”的唯一原因是“switchMap”只会返回一个可观察值。本质上,他所做的是返回多个操作的解决方法。但是,使用“mergeMap”我们可以正确返回多个操作。 (2认同)