Alexander Zalishchuk
Alexander Zalishchuk

Reputation: 47

Inject Angular services to Redux action creators

Any ideas how to inject angular services like $http or $q to use them in Redux action creators? Now I am using third-party library to make HTTP requests. Using this action creator as angular service is unsuitable for me, because it can be called from non-angular conditions. Also, I am using ng-redux to connect Angular with Redux.

Now my action creator looks like this:

export function fetchContentItems() {
  return (dispatch) => {
    dispatch(requestContentItems());

    return axios(API_URL)
      .then(({ data }) => {
        dispatch(setContentCount(data.count));
        dispatch(receiveContentItems(data.items));
      });
  };
}

Non-angular conditions I talked about before:

export function setFilterOption(option, value) {
  return (dispatch, getState) => {
    dispatch({
      type: SET_FILTER_OPTION,
      option,
      value
    });

    dispatch(fetchContentItems());
  };
}

Upvotes: 2

Views: 720

Answers (2)

Irwing Herrera
Irwing Herrera

Reputation: 11

you could add effects to send call your service when the dispach is sent to call and with a pipe wait for the answer or error and each one who sends his dispach.

enter image description here

Upvotes: 0

creimers
creimers

Reputation: 5303

Mighty late, but this is what I ended up doing (ES6):

Action creators inside of an angular service:

class ActionService {
  constructor($http, $q) {
    this.$http = $http;
    this.$q = $q;
  }

  fetchRequest() {
    return {
      type: 'REQUEST',
      isFetching: true
    };
  }

   fetchSuccess(result) {
    return {
      type: 'REQUEST',
      isFetching: true,
      result: result
    };
  }

  fetchMyResource() {
    return dispatch => {
      dispatch(this.retchRequest())
      return this.$http.get('/my-resource')
      .then(response => {
        return dispatch(this.fetchSuccess(response));
      }
    }
  }

}

Then in your controller, you can do something like this:

class Controller{
  constructor($ngRedux, ActionService) {
    this.$ngRedux = $ngRedux;
    this.ActionService = ActionService;
  }
  
  getMyResource() {
    this.$ngRedux.dispatch(this.ActionService.fetchMyResource());
  }
}

Upvotes: 1

Related Questions