在 ngrx/effect 中访问存储的正确方法

mr_*_*ash 7 javascript ngrx ngrx-effects angular ngrx-store

我正在使用 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})
    })
)
Run Code Online (Sandbox Code Playgroud)

这是getData1选择器:

export const getData1= createSelector(
  getItems,
  getIndexes,
  (items, indexes) => {
    console.log('HI, I AM getData1');
    return transformItems(items, indexes);
  }
);
Run Code Online (Sandbox Code Playgroud)

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

所以getData1选择器从存储中获取数据取决于另一个名为handleItemsChanges. handleItemsChanges每次与项目相关的更改都会触发效果并重新计算。结果,在saveAll我变得不实际state.items。我究竟做错了什么?可能我应该使用另一个操作员,withLatestFrom或者解决方案是什么?谢谢

PS顺便说一句,我withLatestFrom每次想从商店获取一些数据时都会使用。这是正确的吗?

Der*_*ang 2

你需要在被解雇handleItemsChanges之前先采取行动saveAll。一种方法是对操作创建效果handleItemsChanges并触发save操作。

框架将保证执行顺序(handleItemsChanges先然后save),这样withLatestFrom操作就会按您的预期进行。