Javascript 如何使用$http为RESTAPI调用创建通用服务?
我想要通用服务,我将从我的控制器调用它。我希望动态地传递选项 比如说Javascript 如何使用$http为RESTAPI调用创建通用服务?,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,我想要通用服务,我将从我的控制器调用它。我希望动态地传递选项 比如说 var app = angular.module('common', []); app.factroy('APIService', ['$http', function($http){ return { doApiCall: function(url, method, payload, headers){ // I should make a call to server wit
var app = angular.module('common', []);
app.factroy('APIService', ['$http', function($http){
return {
doApiCall: function(url, method, payload, headers){
// I should make a call to server with the parameters passed from the controller.
//
}
}
}]);
app.controller('SampleCtrl', ['$scope', 'common' , function($scope, common){
// I want to call the doApiCall function provided by common service based the application requirements.
common.doApiCall('api/user', 'GET', function(){
});
common.doApiCall('api/user', 'POST', function(){
});
common.doApiCall('api/user', 'DELETE', function(){
});
common.doApiCall('api/user', 'PUT', function(){
});
});
我想要上面这样的东西,但我做不好?请告诉我如何制作用于访问RESTAPI服务的通用函数。提前感谢。我发现您的代码中有两个错误: 1) 将app.factory替换为app.factory 2) 在控制器中,插入应用程序模块而不是服务,请参阅:
app.factory('APIService', ['$http', function($http) {
return {
doApiCall: function(url, method, payload, headers){
// I should make a call to server with the parameters passed
// from the controller.
var xhr = $http({
method: method,
url: url,
headers: headers || {}, // Optional headers
});
// You probably want to differentiate success / error handlers
xhr.success(payload);
xhr.error(payload);
return xhr;
}
};
}]);
app.controller('SampleCtrl', ['$scope', 'APIService' , function($scope, api) {
// You should be able to call your service:
api.doApiCall('api/user', 'DELETE', function(data) {
console.log(data);
});
});
我知道可能有点晚了,但我构建了一个通用的angular web服务api,您可以在其中传入任意数量的参数:
谢谢您提供的错误信息。我在这里寻找对服务器的$http调用。你能帮我一下吗?
$http
的用法在中有很好的解释。我看不出有什么问题。这已经由angular完成了。尝试