AngularJS - 等待多个资源查询完成 [英] AngularJS - wait for multiple resource queries to complete

查看:27
本文介绍了AngularJS - 等待多个资源查询完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a single factory defined with ngResource:

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

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

I am making multiple calls to the query method defined on this factory. The calls can happen asynchronously, but I need to wait for both calls to complete before continuing:

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 添加到我当前的项目中.

Is there a way to do this with AngularJS factories defined with ngResource, similar to jQuery's $.when().then() functionality? I would prefer not to add jQuery to my current project.

推荐答案

你会想要使用 promises 和 $q.all().

You'll want to use promises and $q.all().

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

Basically, you can use it to wrap all of your $resource or $http calls because they return promises.

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 - 等待多个资源查询完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆