在 AngularJs 中同步进行多个 http 调用

make multiple http calls synchronously in AngularJs

我在我的项目中使用 AngularJs。我必须进行多次 http 调用,然后 return 将合并结果显示在我的视图中。如何使用 AngularJs 实现此目的?

请告诉我,因为我不是 AngularJs 方面的专家,需要适当的方法来解决这个问题。

使用承诺API:

var wheatherPromise = $http.get(...);
var timePromise = $http.get(...);

var combinedPromise = $q.all({
    wheather: wheatherPromise,
    time: timePromise
})

combinedPromise.then(function(responses) {
    console.log('the wheather is ', responses.wheather.data);
    console.log('the time is ', responses.time.data);
});

有关详细信息,请参阅 the documentation

  • 在单独的函数中发出你的 $http 请求或者(AJS 服务是 推荐)。
  • 根据您的列表在 for 循环中调用该函数
  • 声明一个作用域变量在函数内部保存一个空数组
  • 推送数组中的响应对象

避免在 for 循环中定义 $http.get,这会导致意外行为