简体   繁体   中英

generic http.post function defination in angularJs

我该如何定义通用函数,即http.post()进行剩余调用。我想在每次需要发布数据时都使用此函数。

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

Below way can be used to do it:

HTTP Service Code:

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

Controller Code:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM