Tim Tim - 3 months ago 9
AngularJS Question

Returning one object with the result of two AJAX GET calls

I'm working on a simple weather app that will grab both the current and the weekly forecast from a weather API. To keep it simple, I'd really like to my

weatherService
function,
getForecast
, to somehow make two AJAX calls -- one for the weekly forecast, which I already have, and one for the current forecast (unfortunately I don't think this API has a means of retrieving a JSON return that contains both). I'm not sure about the best way to go about doing this, I'm very new to Angular.

Here's my service:

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

});


And I'd like a second GET, retrieving from: http://api.openweathermap.org/data/2.5/weather?q=Chicago,IL&appid=e92f550a676a12835520519a5a2aef4b to be appended to the response, so that there's a single object returned.

Also, if this isn't the best way to go about doing this, I'm certainly open to suggestions.

Answer

What you are looking for is angular promises library $q

$q.all([$http(...), $http(...),...]).then(function(ret){
    // ret has all results from all ajax calls         
})

More specifically:

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)     
})

There is excellent video on using $q.all at egghead.io