TypeError:无法读取属性' get'在AngularJS上未定义

时间:2016-03-17 03:55:42

标签: javascript angularjs

我是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;
    });
});

在我的错误所在的地方,我很困惑。错误消息是:

  

TypeError:无法读取属性' get'未定义的   Object.factory.getNotificationList   (http://localhost:63342/EmailNotification/js/email-angular.js:15:21

2 个答案:

答案 0 :(得分:2)

您收到此错误是因为您的工厂中未定义$http

您可以通过将其传递给工厂来修复它:

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

答案 1 :(得分:0)

简单的可能原因是$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();

在这个例子中,虽然变量a,b声明,但第二个函数pqr()将返回NaN,直到我们传递一个参数,显式