我有角度控制器和服务。
控制器调用服务,并传递一些数据和端点。
我的服务执行http请求,但是我正在尝试重构我的代码,以便从控制器传入端点,我的服务尝试匹配数组列表中的端点。
控制器:
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'}
});
}
};
});
根据通过$scope.buttonClick
点击的按钮,会传递任何端点,例如
<button ng-click="buttonClick('ShippingInfo')>Shipping</button>
<button ng-click="buttonClick('addressInfo')>Address</button>
<button ng-click="buttonClick('certDetails')>Cart</button>
答案 0 :(得分:2)
你的endPoints应该是对象
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'}
});
}
};
});
答案 1 :(得分:2)
我建议不要这样做,因为在这种情况下控制器至少需要知道url端点的密钥 拥有以下产品代码会更好:
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'}
});
}
}
在控制器中使用
service.postCertDetails({...your data...});