AngularJS - 在工厂内调用$ http,在控制器$ scope中返回

时间:2017-06-24 10:03:02

标签: angularjs angularjs-http

我认为标题总结了我想要实现的目标。我查看了有关该问题的不同SO线程,有些使用$ q而有些则没有。 所以我试着简单地说:

.factory('db',['$http',function($http){
    return{
        get:function(){
            $http.get('https://randomuser.me/api/');
        }
    }
}])

    .controller('PanelCtrl', [
    '$scope',
    'db',
    function($scope, db){
     db.get().then(function(response){
        $scope.player=response.data;
     });

使用Console.log我发现如果我在控制器/工厂内使用整个调用,则会获取数据。但无论我做什么,我都会在$ scope中获得未定义的结果。对我来说最好的结果是将响应数据从工厂返回到$ scope,这样所有$ http调用都将包含在我的工厂内。

1 个答案:

答案 0 :(得分:2)

更改

$http.get('https://randomuser.me/api/');

return $http.get('https://randomuser.me/api/');

此处需要返回,以便调用者可以参考结果。