Javascript 类型错误:无法读取 AngularJS 上未定义的属性“get”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36051396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: Cannot read property 'get' of undefined on AngularJS
提问by twindicated70
I am new on AngularJS and I got that error. Here is my code:
我是 AngularJS 的新手,我遇到了那个错误。这是我的代码:
app.factory('NotificationService', function($http){
var factory = {};
factory.getNotificationList = function($http){
var url = "http://some/url";
return $http.get(url);
}
return factory;
});
app.controller('NotificationListController', function($scope,$http, NotificationService) {
var notificationList = NotificationService.getNotificationList();
notificationList.then(function(response){
console.log(response);
$scope.notificationData = response.data;
return response;
});
});
I am so confuse where my mistake is. The error message is:
我很困惑我的错误在哪里。错误信息是:
TypeError: Cannot read property 'get' of undefined at Object.factory.getNotificationList (http://localhost:63342/EmailNotification/js/email-angular.js:15:21)
类型错误:无法在 Object.factory.getNotificationList ( http://localhost:63342/EmailNotification/js/email-angular.js:15:21)读取未定义的属性“get”
回答by JanR
You are getting this error because $http
is undefined in your factory.
您收到此错误是因为$http
在您的工厂中未定义。
You can fix it by passing it to the factory like so:
您可以通过将其传递给工厂来修复它,如下所示:
app.factory('NotificationService', ['$http', function ($http) {
var factory = {};
factory.getNotificationList = function() { // Remove the `$http` parameter from here.
var url = "http://some/url";
return $http.get(url);
}
return factory;
}]);
回答by Rajiv Pingale
Simple possible reason is $http
is passed twice. When you pass any argument to the function, the closure for those variable changes
简单的可能原因$http
是通过了两次。当您将任何参数传递给函数时,这些变量的闭包会发生变化
var a =10;
var b= 20;
var abc = function()
{
document.getElementById("first").innerHTML = a + b;
}
var pqr = function(a,b)
{
document.getElementById("second").innerHTML = a + b;
}
abc();
pqr();
In this example, though variable a,b declared, second function pqr()
will return NaN, until we pass an argument, explicitly
在这个例子中,虽然声明了变量 a,b,但第二个函数pqr()
将返回 NaN,直到我们明确地传递一个参数