【问题标题】:Cannot read property of 'get' $http inside a nested function无法在嵌套函数中读取“get”$http 的属性
【发布时间】:2016-05-27 16:16:09
【问题描述】:

我收到以下错误

angular.js:13550 TypeError: Cannot read property 'get' of undefined 在 Object.DataService.getDataFromAPI

这是我搞砸 $HTTP.get 的地方。知道我做错了什么或如何解决吗? 我认为问题在于将 $HTTP 传递给嵌套函数。

(函数(模块){ '使用严格';

DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {


var getDataFromAPI = function ($http) {


        $http.get("http://localhost:34183/myAPI")
        .then(function (response) {
            console.log(response);
            console.log(response.data);
            return response.data;
        });

    };
}
 return {
            getDataFromAPI: getDataFromAPI
};
}

    module.factory('DataService', DataService);

})(angular.module('ClassAPP'));

这是我的代码,如果我直接将 json 嵌入其中,该方法可以正常工作。

 DataService.$inject = ['$http', '$q'];
 function DataService($http, $q) {

 var getDataFromAPI = function ($http) {
        return [{
                  "Grade": "A+",
                  "Class": {
                      "Subject": "Select Topics in Basket Weaving",
                      "Professor": "DJ Khaled"
                  }            
               }];
    };
return {
            getDataFromAPI: getDataFromAPI
};
}
module.factory('DataService', DataService);

})(angular.module('ClassAPP'));

【问题讨论】:

    标签: javascript angularjs http get


    【解决方案1】:

    你需要在工厂内返回对象

    function DataService($http, $q) {
    
    
        var getDataFromAPI = function () {        
    
          return $http.get("http://localhost:34183/myAPI")
                .then(function (response) {
                    console.log(response);
                    console.log(response.data);
                    return response.data;
                });
    
            };
    
          return {
               getDataFromAPI : getDataFromAPI 
           }
        }
    

    【讨论】:

    • 对不起,我把它漏掉了,我认为问题是我无法将 $http 放入方法中
    • 还需要从函数中返回$http服务: var getDataFromAPI = function() { return $http.....
    • 函数是否需要接受 $http 作为参数?
    • 您不需要传递 $http 作为参数,您已经将其注入服务,正如@Rob 指出的,您需要在函数内返回 $http 请求对象,
    【解决方案2】:

    你可以这样写吗?

    app.factory("DataService", ["$http", function($http){
        return {
            getDataFromApi: function(url) {
                return $http.get(url);
            }
        };
    }]);
    

    用法

    getDataFromApi.getDataFromApi('/path/to/api/');
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多