Aoguzie
Aoguzie

Reputation: 35

Multiple GET requests in Angularjs

I want to make multiple ajax calls from different urls in football-data.org API. Here's my code sample:

angular.module('liveFootball', ['ionic'])
.constant('urls', {
    BASE: 'http://api.football-data.org/',
    BASE_API: 'http://api.football-data.org/v1/soccerseasons/',
    TEAM_URL: 'http://api.football-data.org/v1/teams',
    HEAD: {
        'X-Auth-Token': 'e7486677a2dd4260b7aeb8a464749e80'
    }
});
        getAllFixtures: function(leagueID){
            var getAllFixtures = {
                method: 'GET',
                url: urls.BASE + "fixtures?timeFrame=n14",
                headers: urls.HEAD
            }
            return $http(getAllFixtures);
        },

Is there a way I can include another url in this call? Thanks.

Upvotes: 0

Views: 960

Answers (2)

kennasoft
kennasoft

Reputation: 1593

It's not possible to have more than one url field in the $http config object, but you can send the three requests and use Promise.all() $q.all to await their responses. The response will be a promise which when you .then() will have an array containing all the responses.

    getAllFixtures: function(leagueID){
            var sources = [
                 urls.BASE,
                 urls.BASE_API,
                 urls.TEAM_URL
            ];
            var promises = [];
            for(var i=0; i<sources.length; i++){
                promises.push($http({
                    method: 'GET',
                    url: sources[i] + "fixtures?timeFrame=n14",
                    headers: urls.HEAD
                }));
            }
            return  ̶P̶r̶o̶m̶i̶s̶e̶.̶a̶l̶l̶ $q.all(promises);
        }

Upvotes: 2

Ghazanfar Khan
Ghazanfar Khan

Reputation: 3718

There is no way you can include another url , you have to call it again. You can use $q.all in angular to make multiple request at once. For example:

    var request = [getAllFixtures('10'), getAllFixtures('11)];
     $q.all(request).then(function (value) {

     },function(err){

     }

Upvotes: 0

Related Questions