如何为休息调用定义泛型函数,即http.post()。我希望每次需要发布数据时都使用此函数。
答案 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)
可以使用以下方式:
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);
}
});