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

查看:123
本文介绍了如何捆绑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 对象http://docs.angularjs.org/api/ng.$qrel =noreferrer> $ 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.

参数


  • 承诺 - {Array。< Promise>} - 一系列承诺。

  • promises – {Array.<Promise>} – An array of promises.

退货

{Promise} - 返回将使用值数组解析的单个promise,每个值对应于同一索引中的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天全站免登陆