我有一个用 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/