等到$http完成,以便在AngularJS中输出结果

Wait till $http is finished in order to output the result in AngularJS

本文关键字:AngularJS 输出 结果 http 完成 等到      更新时间:2023-09-26

如何使用我的函数等待$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()函数中输出交易时,它包含我从服务器获得的正确数组。

我做错了什么?

$http 和 angularjs 中的所有异步服务都返回一个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) {
        //...
    }
  }
});