2016-12-10 9 views
2

如何注入角色服務(如$http$q)以便在Redux動作創建者中使用它們的任何想法?現在我使用third-party library來發出HTTP請求。使用這個動作創建器作爲角度服務對我來說不合適,因爲它可以從非角度條件調用。另外,我正在使用ng-redux來連接Angular和Redux。向Redux動作創作者注入角度服務

現在我的行​​動的創建者是這樣的:

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

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

無棱角的條件我談到前:

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

    dispatch(fetchContentItems()); 
    }; 
} 
+0

的任何解決方案,嗯? –

回答

0

強大晚了,但是這是我落得這樣做(ES6):

角度服務中的動作創作者:

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

} 

然後在您的控制器,你可以做這樣的事情:

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