[英]How to create generic Service for Rest API Call using $http?
我想要通用服務,我會從我的控制器調用。 我想要動態傳遞選項。
例如。
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.factory替換app.factroy
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);
});
});
我知道它可能有點晚了但我構建了一個通用的角度Web服務api,您可以在其中傳入任意數量的參數:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.