简体   繁体   中英

AngularJS error: Cannot read property 'get' of undefined

I am new to AngularJS and am attempting to retrieve a variable via a $http.get request. I have setup the code similar to a few examples I have seen and am unable to figure out why I am getting the "Cannot read property 'get' of undefined" error message. I have found similar questions on this site but they all pointed to various formatting issues. I could not find one so I am hoping someone may be able to point out what I am doing wrong. Below is my service that is using $http.

(function () {

angular
    .module('golfleague.player')
    .factory('PlayerService', ['$http', function($http){

        var onError = function(data) {
            data.errors = data;

        };

        function getLastName($http) {
            return $http.get('/player/lastname').then(onFetchLastNameComplete, onError);
            function onFetchLastNameComplete(response) {
                return response;
            }

        }

        return {
            getLastName: getLastName
        };

    }]);

})();

You had $http dependency as a parameter inside PlayerService 's getLastName function parameter, and you wanted to use injected $http dependency of service. So while calling getLastName function its parameter value is $http it take preference to current local function variable & kill existence of $http service of PlayerService . As now $http method is undefined you will not get get method defined in it, that's why you are getting an error.

By removing $http from getLastName function parameter will solve your issue.

function getLastName() { //<--removed $http from here
    return $http.get('/player/lastname').then(onFetchLastNameComplete, onError);
     function onFetchLastNameComplete(response) {
            return response;
     }
 }

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