简体   繁体   English

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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