简体   繁体   English

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

[英]make multiple http calls synchronously in AngularJs

I am using AngularJs in my project. 我在我的项目中使用AngularJs。 I have to make multiple http calls and then return the consolidated result to my view. 我必须进行多个http调用,然后将合并的结果返回到我的视图。 How to achieve this using AngularJs? 如何使用AngularJs实现这一目标?

Please let me know since I am not an expert in AngularJs and need a proper approach to solve this. 请告诉我,因为我不是AngularJs的专家,需要一个正确的方法来解决这个问题。

Use the promise API: 使用promise 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);
});

See the documentation for more details 有关详细信息,请参阅文档

  • make ur $http request in a seperated function or (AJS service is recommended). 在分离的函数中创建ur $ http请求或(建议使用AJS服务)。
  • call that function in a for loop based on ur list 基于ur列表在for循环中调用该函数
  • declare a scope variable holds an empty array inside the function 声明一个scope变量在函数内部保存一个空数组
  • push response objects in the array 推送数组中的响应对象

avoid defining $http.get inside a for loop which cause unexpected behavior 避免在for循环中定义$ http.get,这会导致意外行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM