类型错误:无法读取 AngularJS 上未定义的属性“get”

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

本文关键字:未定义 属性 get AngularJS 错误 读取 类型      更新时间:2023-09-26

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

我很困惑我的错误在哪里。错误消息是:

类型错误: 无法读取未定义的属性"get" at Object.factory.getNotificationList (http://localhost:63342/EmailNotification/js/email-angular.js:15:21)

您收到此错误是因为$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;
}]);

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

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