将数组中的项目列表映射到函数参数

Mapping a list of items in an array to a function parameter

我有一个 angular 控制器和服务。

控制器调用服务,并传递一些数据和端点。

我的服务执行 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");                    

            });
    }

我的服务:

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>

你的端点应该是对象

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'}
            });
        }
    };
});

我建议不要那样做,因为在那种情况下控制器至少需要知道 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...});