【问题标题】:Wait till $http is finished in order to output the result in AngularJS等到 $http 完成,以便在 AngularJS 中输出结果
【发布时间】:2015-01-08 10:03:31
【问题描述】:

如何使用我的函数等待 $http 请求完成?

我的services.js 如下所示:

var app = angular.module('starter.services', []);

app.factory('Deals', function($http) {
    function getDeals() {
        $http.get('http://www.domain.com/library/fct.get_deals.php')
        .success(function (data) {
            var deals = data;
            return deals;
        })
        .error(function(err){
      });
  }

  return {
    all: function() {
        return getDeals();
    },
    get: function(keyID) {
        //...
    }
  }
});

我的controllers.js 看起来像:

var app = angular.module('starter.controllers', []);

app.controller('DealCtrl', function($scope, Deals) {
    $scope.deals = Deals.all();
    console.log($scope.deals);
});

我的controllers.js 文件中的console.log 输出“未定义”,但是当我在getDeals() 函数中输出交易时,它包含我从服务器获取的正确数组。

我做错了什么?

【问题讨论】:

    标签: javascript angularjs oop


    【解决方案1】:

    $http 和 angularjs 中的所有异步服务都返回一个 promise 对象。见promise api

    您需要使用then 方法将其分配给范围内的值。

    所以你的控制器:

    app.controller('DealCtrl', function($scope, Deals) {
        Deals.all().then(function (deals) {
            $scope.deals = deals;
            console.log($scope.deals);
        });
    });
    

    您的服务

    app.factory('Deals', function($http) {
        function getDeals() {
            return $http.get('http://www.domain.com/library/fct.get_deals.php')
            .success(function (data) {
                var deals = data;
                return deals;
            });
      }
    
      return {
        all: function() {
            return getDeals();
        },
        get: function(keyID) {
            //...
        }
      }
    });
    

    【讨论】:

    • 感谢您的回答,但此代码会引发以下错误:TypeError: Cannot read property 'then' of undefined
    • @JohnBrunner 您需要将承诺返回给服务中的调用者。更新了代码
    • 非常感谢。现在我没有收到错误,但我还有另一个问题。我的服务器数组看起来像[{id: "1", title: "Title", ...}, ... ],但我无法使用ng-repeat="deal in deals"{{deal.title}} 访问title
    • @JohnBrunner 很高兴我能帮上忙。如果您认为此问题已得到解答,请单击答案附近的复选图标进行标记。但是,cmet 不适合追问,因为它对以后的访问者没有用处,我建议您尝试自己调试它,参考官方文档,如果其他一切都失败了,请打开另一个问题。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    相关资源
    最近更新 更多