我正在使用 Angular 6、ngrx/store、ngrx/effects。
当我按下“保存”按钮时,我有一个应该触发的效果。我正在那里使用 withLatestFrom
来收集我需要将其发送到服务器的所有数据:
@Effect({dispatch: false})
saveAll$ = this.actions$.pipe(
ofType(ActionTypes.Save),
withLatestFrom(
this.store.select(fromReducers.getData1),
this.store.select(fromReducers.getData2),
this.store.select(fromReducers.getData3),
this.store.select(fromReducers.getData4)
),
switchMap(([action, data1, data2, data3, data4]: [ActionType, Data1[], Data2[], Data3[], Data4[]]) => {
// here is some operations with these data
return this.apiService.saveData({data1, data2, data3, data4})
})
)
这是 getData1
选择器:
export const getData1= createSelector(
getItems,
getIndexes,
(items, indexes) => {
console.log('HI, I AM getData1');
return transformItems(items, indexes);
}
);
getItems
,依次返回state.items
。问题是state.items
可以修改成另一种效果:
@Effect()
handleItemsChanges$ = this.actions$.pipe(
ofType(ActionTypes.ChangesInItems),
withLatestFrom(
this.store.select(fromReducers.getItems),
this.store.select(fromReducers.getUsers),
),
switchMap(([action, items, users]: [ActionType, Item[], User[]]) => {
console.log('I AM handleItemsChanges');
const actions = [];
if (itemsShouldBeUpdated) {
actions.push(new UpdateData(changes))
}
})
)
因此 getData1
选择器从存储中获取数据取决于另一个名为 handleItemsChanges
的效果。 handleItemsChanges
效果在每次更改与项目相关的内容并重新计算时触发。
结果,在 saveAll
中,我得到的不是实际的 state.items
。
我究竟做错了什么?可能我应该使用 withLatestFrom
的另一个运算符或者什么是解决方案?谢谢
附言顺便说一句,每次我想从商店获取一些数据时,我都在使用 withLatestFrom
。是否正确?
最佳答案
您需要在触发 saveAll
之前触发操作 handleItemsChanges
。一种方法是对 handleItemsChanges
操作产生效果并触发 save
操作。
框架将保证执行顺序(先是handleItemsChanges
,然后是save
),这样withLatestFrom
操作就会按预期工作。
关于javascript - 在 ngrx/effect 中访问商店的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50749252/