如何捆绑 Angular $http.get() 调用? [英] How to bundle Angular $http.get() calls?

查看:24
本文介绍了如何捆绑 Angular $http.get() 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器需要检索两个单独的 REST 资源,这些资源将填充两个下拉列表.我想避免在 $http.get() 调用返回之前填充它们中的任何一个,以便下拉列表似乎同时填充,而不是一个接一个地滴入.

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.

是否可以捆绑 $http.get() 调用并优雅地为两个返回的数组设置 $scope 变量,而不必为两种场景编写状态逻辑,例如a 在 b 之前返回,b 在 a 之前返回?

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?

推荐答案

调用Angular的返回值$http 函数是一个使用 $ 的 Promise 对象q(受 Kris Kowal 的 Q 启发的承诺/延迟实现).

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).

看看$q.all(promises)方法文档:

将多个承诺组合成一个承诺,当所有输入承诺都已解决.

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

参数

  • promises – {Array.<Promise>} – 一个承诺数组.
  • promises – {Array.<Promise>} – An array of promises.

退货

{Promise} – 返回将使用值数组解析的单个承诺,每个值对应于承诺数组中相同索引处的承诺.如果任何 promises 被拒绝解决,这个产生的承诺将被同样的拒绝解决.

{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 the promises is resolved with a rejection, this resulting promise will be resolved with the same rejection.

您可以使用 $q.all 来加入"您的 http 调用的结果,代码类似于:

You can use $q.all to "join" the results of your http calls, with code similar to:

app.controller("AppCtrl", function ($scope, $http, $q) {

  $q.all([
    $http.get('/someUrl1'),
    $http.get('/someUrl2')
  ]).then(function(results) {
     /* your logic here */
  });
}

这篇关于如何捆绑 Angular $http.get() 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆