简体   繁体   中英

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

I am new on AngularJS and I got that error. 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 )

You are getting this error because $http is undefined in your factory.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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