【问题标题】:AngularJS - $http call inside factory to be returned in controller $scopeAngularJS - 工厂内的 $http 调用将在控制器 $scope 中返回
【发布时间】:2017-06-24 18:05:28
【问题描述】:

我认为标题很好地总结了我想要实现的目标。我查看了有关该问题的不同 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 调用都将包含在我的工厂中。

【问题讨论】:

    标签: angularjs angularjs-http


    【解决方案1】:

    改变

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

    到

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

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

    【讨论】:

    • 仍然返回 undefined for console.log($scope.player);
    • @Johnny 请更新您的问题,并发布确切的错误。
    • @Johnny - 当您将console.log(response) 作为.then() 的第一行写入时,您会在控制台中得到什么?
    • 我得到一个具有数据、标题、配置等属性的对象,显然问题出在 $scope 分配上?@31piy
    • @Johnny - 因为在您尝试记录数据时数据不存在。您已经进行了异步调用,因此您需要确保仅在数据从服务器返回之后才对数据进行处理,即在 then 块内。该块中的代码只有在数据返回后才会执行(因此使用了then这个词)。
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多