angularJs中的通用http.post函数定义

时间:2016-05-23 15:21:48

标签: javascript angularjs

如何为休息调用定义泛型函数,即http.post()。我希望每次需要发布数据时都使用此函数。

2 个答案:

答案 0 :(得分:1)

app.factory("apiService", ["$http", function($http){
    return {
        postTheThing: function(url, payload) {
            return $http({
                url: url,
                method: 'POST',
                data: payload
            });
        }
    }
}]);

app.controller('MainCtrl', ['apiService', '$scope', function(apiService, $scope){
    apiService.postTheThing('path/to/stuff', myPayload).then(function(response){
        //do stuff with response
    }).catch(function(error){
        //an error
    });
}]);

答案 1 :(得分:1)

可以使用以下方式:

HTTP服务代码:

app.service('HTTP', function($http) {
    this.post = function(url, data, successCallback, failureCallback) {
        $http({
           method: 'POST',
           url: url,
           data: data
         }).then(function(response) {
             successCallback(response);
         }, function(response) {
             failureCallback(response);
         });
    };

    this.put = function(url, data, successCallback, failureCallback) {
        $http({
           method: 'PUT',
           url: url,
           data: data
         }).then(function(response) {
             successCallback(response);
         }, function(response) {
             failureCallback(response);
         });
    };
});

控制器代码:

app.controller('MyCntrl', function($scope, HTTP) {
    function successHandler(res) {
        // @TODO response
    }
    function failureHandler(res) {
       // @TODO response
    }

    $scope.postData = function() {
        HTTP.post('/someurl', {}, successHandler, failureHandler);
    }
});