首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回一个带有两次AJAX GET调用结果的对象

返回一个带有两次AJAX GET调用结果的对象
EN

Stack Overflow用户
提问于 2016-08-09 07:19:44
回答 2查看 29关注 0票数 1

我正在开发一个简单的天气应用程序,它将从天气API获取当前和每周的天气预报。为了简单起见,我真的想让我的weatherService函数getForecast以某种方式进行两个AJAX调用--一个用于每周的天气预报,我已经有了,另一个用于当前的天气预报(不幸的是,我不认为这个API有办法检索包含两者的JSON返回)。我不确定做这件事的最好方法是什么,我对Angular非常陌生。

这是我的服务:

代码语言:javascript
复制
weather.service('weatherService', function($resource, $http){

    this.currentForecast = null;

    // default city
    this.city = 'Chicago, IL';

    this.getForecast = function(location, type) {

            return $http({
                method : "GET",
                url : "http://api.openweathermap.org/data/2.5/forecast/daily?q="+location+"&mode=json&cnt=7&appid=e92f550a676a12835520519a5a2aef4b"
            }).then(
                 function(response) {
                     return response.data;
                 }
            )
    };

});

我想要第二个GET,retrieving:http://api.openweathermap.org/data/2.5/weather?q=Chicago,IL&appid=e92f550a676a12835520519a5a2aef4b被追加到响应中,这样就只返回一个对象。

此外,如果这不是做这件事的最好方法,我当然愿意接受建议。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-09 07:26:07

您正在寻找的是angular promises库$q

代码语言:javascript
复制
$q.all([$http(...), $http(...),...]).then(function(ret){
    // ret has all results from all ajax calls         
})

更确切地说:

代码语言:javascript
复制
weather.service('weatherService', function($resource, $http, $q){

  this.getForecast = function(location, type) {
     return $q.all([
         $http.get(url1(location, type)), 
         $http.get(url2(location, type))
     ])
  }

})


...


weatherService.getForcast(location, type).then(function(ret){ 
    console.log(ret[0].data)
    console.log(ret[1].data)     
})

egghead.io上有关于使用$q.all的优秀视频

票数 1
EN

Stack Overflow用户

发布于 2016-08-09 07:22:01

嗯,你可以使用webworkers,但是你有6个问题。您还可以使用then回调链接请求。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38839852

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档