【发布时间】:2020-03-10 18:29:07
【问题描述】:
我的商店有两个字段:
items: Item[]money: number
当用户购买物品时我调用apiService如果服务器的响应允许你添加一个物品(服务器会检查用户是否有足够的钱)我可以做两个我商店的变化:
- 将新项目推入数组
- 减少金钱
我对调度操作的良好做法感到困惑...... 哪种方式最好?
- 多分派 - 分派
AddItem动作和DecreaseMoney动作:
store.dispatch([new AddItem(), new DecreaseMoney()]);
- 订阅
AddItem动作并在第一次成功时调度DecreaseMoney动作:
this.actions$.pipe(ofActionSuccessful(AddItem)).subscribe(() => {store.dispatch(new DecreaseMoney()});
- 在
AddItem操作中发送DecreaseMoney操作:
@Action(AddItemAction)
AddItem({ getState, setState }: StateContext<any>) {
const state = getState();
return this.http.post(`${apiUrl}/buy`, {}).pipe(
tap(newItem => {
setState({...state, items: [...state.items, newItem]});
dispatch(new DecreaseMoney()); // <---
})
);
}
【问题讨论】: