我是 AngularJS 新手,正在尝试通过 $http.get 请求检索变量。我已经设置了类似于我见过的一些示例的代码,但无法弄清楚为什么我收到“无法读取未定义的属性'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
};
}]);
})();
最佳答案
您有$http
依赖项作为 PlayerService
内的参数的getLastName
函数参数,并且您想使用注入(inject) $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;
}
}
关于javascript - AngularJS错误: Cannot read property 'get' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35688941/