AngularJS - 等待多个资源查询完成

标签 angularjs

我有一个用 ngResource 定义的工厂:

App.factory('Account', function($resource) {
    return $resource('url', {}, {
        query: { method: 'GET' }
    });
});

我正在多次调用此工厂上定义的查询方法。这些调用可以异步发生,但我需要等待两个调用完成才能继续:

App.controller('AccountsCtrl', function ($scope, Account) {
    $scope.loadAccounts = function () {
        var billingAccounts = Account.query({ type: 'billing' });
        var shippingAccounts = Account.query({ type: 'shipping' });

        // wait for both calls to complete before returning
    };
});

有没有办法用 ngResource 定义的 AngularJS 工厂来实现这一点,类似于 jQuery 的 $.when().then() 功能?我不想将 jQuery 添加到我当前的项目中。

最佳答案

您需要使用 Promise 和 $q.all() .

基本上,您可以使用它来包装所有 $resource 或 $http 调用,因为它们返回 promise 。

function doQuery(type) {
   var d = $q.defer();
   var result = Account.query({ type: type }, function() {
        d.resolve(result);
   });
   return d.promise;
}

$q.all([
   doQuery('billing'),
   doQuery('shipping')
]).then(function(data) {
   var billingAccounts = data[0];
   var shippingAccounts = data[1];

   //TODO: something...
});

关于AngularJS - 等待多个资源查询完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15299850/

相关文章:

javascript - 用鼠标点击输入和用tab选择有什么区别?

javascript - 从 Angular JS 的 Controller 启用 CORS

javascript - Jasmine 测试对象在 Ajax 方法 spy 调用上的状态

javascript - 为什么不显示 HTML

javascript - 捕获 flask 应用程序中的所有路径

javascript - 无法使用 ng-show 更改登录按钮的名称

html - float 右 div 间歇性地推出对齐 - angularjs 模板问题?

javascript - 如何将参数传递给 Angular 服务或工厂?

javascript - AngularJS Scope.on 和scope.emit 在过滤器中的调用顺序

javascript - 类型错误 : Cannot set property '10' of undefined with angularjs