我有一个州解析为:
resolve: {
accounts: function(utils) {
return utils.getAccounts();
},
data: function(utils) {
return utils.getData();
},
termsData: function(utils) {
return utils.getTerms();
}
}
我需要确保仅在角度data
返回termsData
后才会调用accounts
和resolve
。
getAccounts函数类似于:
function getAccounts() {
var deferred = $q.defer();
Restangular.setBaseUrl(baseUrl());
var accountsService = Restangular.all(accountsUrl);
accountsService.post({headers}).then(function(data) {
deferred.resolve(data);
}, function(ex) {
deferred.reject(ex);
});
return deferred.promise;
}
答案 0 :(得分:2)
您可以像我在控制器中所做的那样添加帐户作为依赖项:
resolve: {
accounts: function(utils) {
return utils.getAccounts();
},
data: ['accounts', 'utils', function(accounts, utils) {
accounts.then(function(data){
return utils.getData();
}, function(data){
return $q.reject();
});
}]
}
}
答案 1 :(得分:0)
一旦getTerms
函数承诺得到解决,您就可以调用其他两个函数,然后使用$q.all
& resolve: {
accounts: function(utils, $q) {
return utils.getAccounts().then(function(accounts){
return $q.all([accounts, utils.getData(), utils.getTerms()])
});
}
}
承诺app.controller('mainCtrl', function($q, $scope, accounts){
console.log("accounts", accounts[0])
console.log("getData Response", accounts[1])
console.log("getTerms Response", accounts[2])
})
。
{{1}}
<强>控制器强>
{{1}}
答案 2 :(得分:-1)
假设您需要异步获取所有数据,您可以简单地重构代码以利用promise模式。
var getAccounts = function(...) {
return new Promise(resolve, reject) {
... do something and resolve or reject
};
};
var getTermsData = funciton= function(...) {
return new Promise(resolve, reject) {
... do something and resolve or reject
};
};
var getData = = function(...) {
return new Promise(resolve, reject) {
... do something and resolve or reject
};
};
getAccounts.then(function(accounts) {
return getTermData();
}.then(function(termData) {
return getData(data);
}.catch(function() {
// something went wrong!
}