简体   繁体   English

TypeError:无法读取AngularJS上未定义的属性“ get”

[英]TypeError: Cannot read property 'get' of undefined on AngularJS

I am new on AngularJS and I got that error. 我是AngularJS的新手,但遇到了该错误。 Here is my code: 这是我的代码:

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 ) TypeError:无法读取Object.factory.getNotificationList( http:// localhost:63342 / EmailNotification / js / email-angular.js:15:21 )中未定义的属性“ get”

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;
}]);

Simple possible reason is $http is passed twice. 一个简单的可能原因是$http传递了两次。 When you pass any argument to the function, the closure for those variable changes 将任何参数传递给函数时,这些变量的闭包都会更改

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,直到我们明确传递参数为止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM