javascript 如何捆绑 Angular $http.get() 调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15726377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to bundle Angular $http.get() calls?
提问by brushleaf
I have a controller that needs to retrieve two separate REST resources that will populate two dropdowns. 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.
我有一个控制器需要检索两个单独的 REST 资源,这些资源将填充两个下拉列表。我想避免在 $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, e.g. a returns before b, b returns before a?
是否可以捆绑 $http.get() 调用并优雅地为两个返回的数组设置 $scope 变量,而不必为两种情况编写状态逻辑,例如 a 在 b 之前返回,b 在 a 之前返回?
回答by Kevin Hakanson
The return value of calling the Angular $httpfunction is a Promise
object using $q(a promise/deferred implementation inspired by Kris Kowal's Q).
调用 Angular $http函数的返回值是一个Promise
使用$q的对象(受Kris Kowal 的 Q启发的承诺/延迟实现)。
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.
Parameters
- promises –
{Array.<Promise>}
– An array of promises.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. If any of thepromises
is resolved with a rejection, this resulting promise will be resolved with the same rejection.
将多个承诺组合成一个单一的承诺,当所有的输入承诺都被解决时,这个承诺就会被解决。
参数
- 承诺 –
{Array.<Promise>}
– 一系列承诺。退货
{Promise}
– 返回将使用值数组解析的单个承诺,每个值对应于承诺数组中相同索引处的承诺。如果其中任何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 */
});
}
回答by Sudhir Bastakoti
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
回答by user1007983
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 个调用,然后在两者都完成后调用一个回调。