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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:34:26  来源:igfitidea点击:

TypeError: Cannot read property 'get' of undefined on AngularJS

javascriptangularjs

提问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 $httpis 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 $httpis passed twice. When you pass any argument to the function, the closure for those variable changes

简单的可能原因$http是通过了两次。当您将任何参数传递给函数时,这些变量的闭包会发生变化

see the example here

看这里的例子

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,直到我们明确地传递一个参数