1

我想知道是否有办法监听已在 redux 中成功调度的操作?

在 Angular 的 ngxs 状态管理库中,我可以执行以下操作:

ngOnInit() {
  this.actions$
    .pipe(
      ofActionSuccessful(AddedThingToDo),
      map((event: AddedThingToDo) => event.thingToDo),
      tap(thingToDo => console.log('Action was successfully dispatched'))
    )
   .subscribe();
}

当我知道AddedThingToDo已成功分派时,我可以在其中执行操作。这可能类似于关闭模式,或者可能调度另一个动作。

我正在使用ng-reduxAngular 1.x,但是我认为原理应该与 react redux 相同。

我一直在解决它的唯一方法是在我的操作中进行回调,但感觉非常错误:

export const addThingToDo = (model: IThingToDo, onSuccess?: (model: IThingToDo) => void) =>
  async (dispatch: Dispatch) => {
    dispatch(addingThingToDo());
    try {
      const createdItem = await api.post<IThingToDo>(url, model);
      dispatch(addedThingToDo(createdItem));
      if (onSuccess) {
        onSuccess(createdItem);
      }
    }
    catch (ex) {
      dispatch(addThingToDoFailure(ex));
    }
  };
4

1 回答 1

0

原来redux-thunk支持返回承诺,所以我可以只返回一个承诺而不是使用回调方法。

export const addThingToDo = (model: IThingToDo) =>
  async (dispatch: Dispatch): Promise<IThingToDo> =>
    await new Promise<IThingToDo>(async (resolve, reject) => {
      dispatch(addingThingToDo());
      try {
        const newItem = await api.post<IThingToDo>(url, model);
        dispatch(addedThingToDo(newItem));
        resolve(newItem);
      } catch (ex) {
        dispatch(addThingToDoFailure(ex));
        reject(ex);
      }
    });


this.addThingToDo(thingToDo)
  .then(t => navigateTo(`/things-to-do/${t.id}`));
于 2018-11-19T10:19:32.413 回答