[英]How to bundle Angular $http.get() calls?
I have a controller that needs to retrieve two separate REST resources that will populate two dropdowns. 我有一个控制器,需要检索两个单独的REST资源,将填充两个下拉列表。 I would like to avoid populating either of them until both $http.get() calls have returned, so that the dropdowns appear to be populated at the same time, instead of trickling in one after the other.
我想避免填充其中任何一个,直到两个$ http.get()调用都返回,这样下拉列表似乎同时填充,而不是一个接一个地插入。
Is it possible to bundle $http.get() calls and elegantly set the $scope variables for both returned arrays, without having to write state logic for both scenarios, eg a returns before b, b returns before a? 是否可以捆绑$ http.get()调用并优雅地为两个返回的数组设置$ scope变量,而不必为两个场景编写状态逻辑,例如b之前的返回,b之前返回?
The return value of calling the Angular $http function is a Promise
object using $q (a promise/deferred implementation inspired by Kris Kowal's Q ). 调用Angular $ http函数的返回值是使用$ q的
Promise
对象(受Kris Kowal的Q启发的promise / deferred实现)。
Take a look at the $q.all(promises)
method documentation: 看一下
$q.all(promises)
方法文档:
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
将多个promise组合成一个promise,在解析所有输入promise时解析。
Parameters
参数
- promises –
{Array.<Promise>}
– An array of promises.promises -
{Array.<Promise>}
- 一系列承诺。Returns
返回
{Promise}
– Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array.{Promise}
- 返回将使用值数组解析的单个promise,每个值对应于promises数组中相同索引处的promise。 If any of thepromises
is resolved with a rejection, this resulting promise will be resolved with the same rejection.如果任何
promises
通过拒绝得到解决,那么这个承诺将以相同的拒绝解决。
You can use $q.all
to "join" the results of your http calls, with code similar to: 您可以使用
$q.all
来“加入”您的http调用的结果,代码类似于:
app.controller("AppCtrl", function ($scope, $http, $q) {
$q.all([
$http.get('/someUrl1'),
$http.get('/someUrl2')
]).then(function(results) {
/* your logic here */
});
}
do you mean something like this: 你的意思是这样的:
function someController( $scope, $http, $q ) {
var first_meth = $http.get("first_url"),
second_meth = $http.get("second_url");
$q.all([first_meth, second_meth]).then(function(all_your_results_array) {
//here you'll get results for both the calls
});
}
Ref: Angular JS Doc 参考: Angular JS Doc
You could use the Async javsscript library here: https://github.com/caolan/async . 你可以在这里使用Async javsscript库: https : //github.com/caolan/async 。
Use the series call. 使用系列调用。 It will make the 2 calls and then call one callback when both are done.
它将进行2次调用,然后在完成两次调用时调用一次回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.