Angular 解析action creator中的异步函数

Angular 解析action creator中的异步函数,angular,asynchronous,redux,thunk,Angular,Asynchronous,Redux,Thunk,我正在尝试在更新状态之前在我的操作创建者中解析此异步调用。我试图实现redux thunk,但我对它和angular4+整体来说还是相当陌生的 以下是我的动作创造者的样子: @Injectable() export class IndexActions { constructor( private _cloudReadService: CloudReadService ) {} static UPDATE_INDEX = 'UPDATE_INDEX'; updateI

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

以下是我的动作创造者的样子:

@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中间件中使用服务方法,或者是否有其他方法


非常感谢您提供的任何帮助。

您可以这样做的一种方法是分派三个单独的操作

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
    )
  )
);
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()


我以为我以前试过这样的东西,但没用。这次是这样!但是我不得不改变一些事情。我必须分派成功和错误函数,并用“this”预先结束它们的调用