简体   繁体   English

AngularJS工厂服务返回“未定义”

[英]AngularJS factory service returns 'undefined'

I've tried other answers with the same problem, but none of them worked. 我已经尝试过其他具有相同问题的答案,但是没有一个起作用。 I have the issue where I'm calling my factory and I get the undefined return. 我在打电话给我的工厂时遇到问题,我得到了undefined回报。

Controller (main.js): 控制器(main.js):

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

Factory (beam.js): 工厂(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;
});

Console: 安慰:

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

Your APIuser() doesn't return anything. 您的APIuser()不返回任何内容。 You need to return the promise and in controller wait for promise to resolve before assigning or logging any of the data 您需要返回promise,并在控制器中等待promise解析,然后再分配或记录任何数据

In factory 在工厂

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

In controller 在控制器中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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