Reputation: 8661
I have an angular controller and service.
The controllers calls the service, and passes some data and an endpoint.
My service performs the http request, however i am trying to refactor my code so that i pass in an endpoint from my controller, and my service tries to match the endpoint from a list of array.
Controller:
app.controller('MyController', function($scope, myService) {
$scope.buttonClick = function(endpoint) {
myService.postAction(endPoint, $scope.postData)
.success(function (data, status, headers, config) {
console.log("success");
})
.error(function (data, status, headers, config) {
console.log("error");
});
}
MyService:
app.factory('MyService', function ($http) {
var endPoints = [
'cart/cartDetails',
'customer/addressInfo',
'payment/ShippingInfo',
]
return {
postAction: function(endPoint, postData) {
return $http({
method: 'POST',
url: endPoint,
data: postData,
headers: {'Content-Type': 'application/json'}
});
}
};
});
Depending on what button is clicked via $scope.buttonClick
, any of the endpoints are passed, e.g.
<button ng-click="buttonClick('ShippingInfo')>Shipping</button>
<button ng-click="buttonClick('addressInfo')>Address</button>
<button ng-click="buttonClick('certDetails')>Cart</button>
Upvotes: 0
Views: 53
Reputation: 1417
I suggest not to do that, cause controller in that case need to know at least key of the url endpoint It would be much better to have the following, your factory code:
var endPoints = {'certDetails': 'cart/cartDetails',
'addressInfo': 'customer/addressInfo',
'shippingInfo': 'payment/ShippingInfo'}
return {
postCertDetails: post(endPoints['certDetails']),
postAddressInfo: post(endPoints['addressInfo']),
postShippingInfo: post(endPoints['shippingInfo'])
};
function post(endpoint){
return function(postData){
return $http({
method: 'POST',
url: endpoint,
data: postData,
headers: {'Content-Type': 'application/json'}
});
}
}
usage in controller
service.postCertDetails({...your data...});
Upvotes: 2
Reputation: 703
Your endPoints should be object
app.factory('MyService', function ($http) {
var endPoints = {'certDetails': 'cart/cartDetails','addressInfo': 'customer/addressInfo','ShippingInfo': 'payment/ShippingInfo'}
return {
postAction: function(endPoint, postData) {
return $http({
method: 'POST',
url: endPoints[endPoint],
data: postData,
headers: {'Content-Type': 'application/json'}
});
}
};
});
Upvotes: 2