我想要从我的 Controller 调用的通用服务。我希望动态传递选项。
例如。
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(){
});
});
我想要像上面这样的东西,但我做不到?谁能告诉我如何制作用于访问 REST API 服务的通用函数。提前致谢。
最佳答案
我在您的代码中看到两个错误:
1) 将 app.factroy 替换为 app.factory
2)在您的 Controller 中,您注入(inject)您的应用程序模块而不是您的服务,请参阅:
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);
});
});
关于javascript - 如何使用 $http 为 Rest API 调用创建通用服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20839451/