我是AngularJS的新手,我正在尝试通过$ http.get请求检索变量。我已经设置了类似于我见过的一些示例的代码,我无法弄清楚为什么我得到“无法读取属性'获取'未定义的”错误消息。我在这个网站上发现了类似的问题,但他们都指出了各种格式问题。我找不到一个,所以我希望有人可以指出我做错了什么。以下是我使用$ http的服务。
(function () {
angular
.module('golfleague.player')
.factory('PlayerService', ['$http', function($http){
var onError = function(data) {
data.errors = data;
};
function getLastName($http) {
return $http.get('/player/lastname').then(onFetchLastNameComplete, onError);
function onFetchLastNameComplete(response) {
return response;
}
}
return {
getLastName: getLastName
};
}]);
})();
答案 0 :(得分:0)
您有$http
个依赖项作为PlayerService
getLastName
函数参数中的参数,并且您希望使用注入的$http
服务依赖项。因此,在调用getLastName
函数时,其参数值为$http
,它优先于当前本地函数变量&杀死$http
PlayerService
服务的存在。由于现在$http
方法未定义,因此您不会在其中定义get
方法,这就是您收到错误的原因。
从$http
功能参数中删除getLastName
将解决您的问题。
function getLastName() { //<--removed $http from here
return $http.get('/player/lastname').then(onFetchLastNameComplete, onError);
function onFetchLastNameComplete(response) {
return response;
}
}