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

查看:193
本文介绍了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的$。当(这样做),然后()功能?我想preFER不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.

推荐答案

您需要使用的承诺和 $ Q 。所有()

基本上,你可以用它来包装所有的$资源或$ 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天全站免登陆