2016-02-28 64 views
1

我是AngularJS的新手,试图通过$ http.get请求获取变量。我已经设置了类似于我见过的几个示例的代码,并且无法弄清楚为什么我得到“无法读取属性”获取“未定义的”错误消息。我在这个网站上发现了类似的问题,但他们都指出了各种格式问题。我找不到一个,所以我希望有人能够指出我做错了什么。以下是我使用$ http的服务。AngularJS错误:无法读取未定义的属性'get'

(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 
     }; 

    }]); 

})(); 

回答

0

你有$http依赖为PlayerServicegetLastName函数参数里面的参数,你想用注射服务的$http依赖。因此,在调用getLastName函数时,其参数值为$http它优先考虑当前的本地函数变量&终止PlayerService的服务。如现在$http方法未定义,您不会得到get方法中定义的方法,这就是为什么你会收到错误。

通过从getLastName中删除$http函数参数将解决您的问题。

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