如何链角度$ http.get()调用? [英] How to chain Angular $http.get() calls?

查看:143
本文介绍了如何链角度$ 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()调用,优雅设置$范围内的变量为返回数组,而无需编写状态逻辑这两种情况下,例如B前面一个回报,之前A B回报?

Is it possible to chain $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 功能使用无极 $ q (承诺/延期执行由克里斯·科瓦尔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(承诺)方法的文档:

将多个承诺变成一个承诺,解决了当
  所有的输入承诺得到解决。

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

参数


      
  • 承诺 - {阵列<承诺方式>} - 承诺的数组

  •   
  • promises – {Array.<Promise>} – An array of 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调用的结果,类似于code:

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 */
  });
}

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

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