在$匿名函数中注入$ http服务

时间:2016-10-13 17:13:28

标签: angularjs anonymous-function

我正在尝试将$ http注入我的提供者的$ get中,以便在动态创建的函数中使用。它构建了函数,我的控制器成功调用了函数,但是在创建的函数内部,它出现错误$http is not defined。是否有另一种方法来注入此依赖项以使其可用?

(function(){
    angular.module('app').provider('rest', rest);

    function rest(){
        endpointObjs = [];
        return {

            addEndpoint:function(name, request, endpoint){
                obj = {};
                obj.name = name;
                obj.request = request;
                obj.endpoint = endpoint;
                endpointObjs.push(obj);

            },
            $get:['$http', function($http){

                endpoints = [];
                for(i=0;i<endpointObjs.length;i++){
                    endpoints[endpointObjs[i].name] = new Function("return $http({ url:'" + endpointObjs[i].endpoint + "', method:'" + endpointObjs[i].request + "'});")
                }

                return {endpoints:endpoints};
            }]
        };
    }
})();

编辑:

我的最终目标是创建一个提供程序,允许某人在应用程序的配置中配置所有其他端点,然后他们可以将提供程序注入其控制器并调用他们在配置中定义的自动生成的函数,即。

config.js restProvider.addEndpoint("allSoftware", "GET", "software/all");

controller.js rest.endpoints.allSoftware().then(function(data){....});

1 个答案:

答案 0 :(得分:0)

new Function创建的函数不会创建绑定到其创建上下文的闭包;它们总是在全球范围内创建。

相反,请使用function expression

$get:['$http', function($http){

    endpoints = [];
    for(let i=0;i<endpointObjs.length;i++){
        let config = {
            url: endpointObjs[i].endpoint,
            method: endpointsObj[i].request
        };
        let fn = function() { return $http(config) };
        endpoints[endpointObjs[i].name] = fn;
    };

    return {endpoints:endpoints};
}]

除了能够创建绑定到其创建上下文的闭包之外,函数表达式在使用其余代码进行解析时效率更高。

  

所以最终我希望这允许从控制器传递参数

然后在函数表达式中添加params参数:

 let fn = function(params) {
      if (params) {
          config.params = params;
      }; 
      return $http(config);
 };