angular - 解决 Action 创建者中的异步函数

标签 angular asynchronous redux thunk

我正在尝试在状态更新之前在我的操作创建器中解决此异步调用。我尝试实现 redux thunk,但我对它和 angular4+ 整体来说还很陌生。

这是我的 Action 创建者的样子:

@Injectable() 
export class IndexActions {
  constructor(
    private _cloudReadService: CloudReadService
  ) {}
  static UPDATE_INDEX = 'UPDATE_INDEX';

  updateIndex(): ActionWithPayload {
    return {
      type: IndexActions.UPDATE_INDEX,
      payload: this._cloudReadService.getRecordsByOwner()
        .then(response => {return response})
        .catch(err => console.log)
    }
  }
}

我在 thunk 方面遇到的主要问题是我的服务方法没有在实际的 thunk 中定义。

该服务的基本结构如下:

@Injectable()
export class CloudReadService {
  constructor() {
  }

  getRecordsByOwner(): any {
    return firebase.database()
      .ref('lists/records/owners')
      .orderByChild('ownerName')
      .once('value')
      .then(snapshot => {
          /* process response */
          return processedResponse;
      }
    })
  }
}

我想我的问题实际上是如何在 redux 中间件中使用服务方法,或者是否有其他方法?

非常感谢任何帮助。

最佳答案

实现此目的的一种方法是分派(dispatch)三个单独的操作。

thunk 中间件添加到您的存储中将允许您从操作中返回带有调度参数的函数,以便您可以调度多个操作。

import thunkMiddlware from 'redux-thunk';

const store = createStore(
  // reducer
  rootReducer,
  // preloadedState
  undefined,
  // compose simply enables us to apply several store enhancers
  // Right now, we are only using applyMiddlware, so this is
  // just future-proofing our application
  compose(
    // Middlware can intercept dispatched actions before they reach the reducer
    // in order to modify it in some way
    applyMiddleware(
      // Thunk allows functions to be returned from action creators
      // so we can do things like dispatch multiple actions in a 
      // single action creator for async actions
      thunkMiddlware
    )
  )
);

然后,您可以通过仅调用 updateIndex() 来适本地分派(dispatch)请求的每个阶段

updateIndexStart(): Action {
 return {
   type: 'UPDATE_INDEX_START'
 };
}

updateIndexSuccess(response): ActionWithPayload  {
 return {
   type: 'UPDATE_INDEX_SUCCESS',
   payload: response
 };
}

updateIndexError(err): ActionWithPayload  {
 return {
   type: 'UPDATE_INDEX_ERROR',
   payload: err
 };
}

updateIndex() {
  return (dispatch) => {
    dispatch(updateIndexStart());
    cloudReadService.getRecordsByOwner()
      .then(response => dispatch(updateIndexSuccess(response)))
      .catch(err => dispatch(updateIndexError(err)));
  };
}

关于angular - 解决 Action 创建者中的异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48634478/

相关文章:

arrays - 我将一个数组传递给 'xlsx' 以获取一个 Excel 文件,但我得到了在每一行中解析的数组元素

javascript - d3 v4 TypeScript DefinitelyTyped Angular2 线与 X 轴上的 ScaleTime

swift - 同步和异步如何与线程安全一起工作?

java - 如何将特定的 ExecutorService 与 @Async 一起使用?

redux - 有条件地获取史诗中的数据

javascript - 使用 localStorage 代替 Redux 或 Context API 可以吗?

javascript - Polyfill 支持 Angular 9 自定义元素?

angular - Angular 中 async/await 和 async/fixture.whenStable 的区别

c# - 对象引用在多层异步等待操作中丢失

reactjs - 有没有办法在 createSlice 中访问全局状态?