我正在开发一个简单的天气应用程序,它将从天气API获取当前和每周的天气预报。为了简单起见,我真的想让我的weatherService函数getForecast以某种方式进行两个AJAX调用--一个用于每周的天气预报,我已经有了,另一个用于当前的天气预报(不幸的是,我不认为这个API有办法检索包含两者的JSON返回)。我不确定做这件事的最好方法是什么,我对Angular非常陌生。
这是我的服务:
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被追加到响应中,这样就只返回一个对象。
此外,如果这不是做这件事的最好方法,我当然愿意接受建议。
发布于 2016-08-09 07:26:07
您正在寻找的是angular promises库$q
$q.all([$http(...), $http(...),...]).then(function(ret){
// ret has all results from all ajax calls
})更确切地说:
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的优秀视频
发布于 2016-08-09 07:22:01
嗯,你可以使用webworkers,但是你有6个问题。您还可以使用then回调链接请求。
https://stackoverflow.com/questions/38839852
复制相似问题