2016-07-04 85 views
0

我已經嘗試了其他答案,但是都沒有工作。我有問題,我打電話給我的工廠,我得到undefined回報。AngularJS工廠服務返回'undefined'

控制器(main.js):

app.controller('MainCtrl', ['$scope','beamAPI', function($scope, beamAPI){ 
    $scope.debug = 'Debug True'; 
    $scope.beamFollowers = 1; 
    console.log(beamAPI('amtraxtge')); 
}]); 

廠(beam.js):

app.factory('beamAPI', function($http) { 
    var APIuser = {}; 
    APIuser = function(user) { 
     $http.get('https://beam.pro/api/v1/channels/' + user). 
     then(function(res){ 
      console.log(res.data); 
      return res.data; 
     }); 
    } 
    return APIuser; 
}); 

控制檯:

undefined  main.js:4 
► Object  beam.js:6 

回答

2

APIuser()不返回任何東西。你需要返回的承諾,並在控制器等待承諾分配或記錄任何數據

的工廠

APIuser = function(user) { 
     // return $http promise 
     return $http.get('https://beam.pro/api/v1/channels/' + user). 
     then(function(res){ 
      console.log('Factory log',res.data); 
      return res.data; 
     }); 
    } 

在控制器之前解決

beamAPI('amtraxtge').then(function(data){ 
    $scope.someProperty = data; 
    console.log('Controller log',data); 
}); 
+0

只返回$ http.get( 'https://beam.pro/api/v1/channels/'+用戶) –