Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs multiple ajax requests optimization

I am still learning Angular JS and have this controller which is making two ajax requests to the lastfm api using different parameters. I want to know when each request has been finished, so that I can display a loading indicator for both requests. I have researched it and read about promises and the $q service but cant get my head around how to incorporate it into this. Is there a better way to set this up? and how can I know when each request is done. Thanks.

angular.module('lastfm')

.controller('ProfileCtrl', function ($scope, ajaxData, usersSharedInformation, $routeParams) {

    var username = $routeParams.user;

    //Get Recent tracks
    ajaxData.get({
        method: 'user.getrecenttracks',
        api_key: 'key would go here',
        limit: 20,
        user: username,
        format: 'json'
    })

    .then(function (response) {

        //Check reponse for error message
        if (response.data.message) {
            $scope.error = response.data.message;
        }  else {
            $scope.songs = response.data.recenttracks.track;
         }

    });

    //Get user info
    ajaxData.get({
        method: 'user.getInfo',
        api_key: 'key would go here',
        limit: 20,
        user: username,
        format: 'json'
    })

    .then(function (response) {

        //Check reponse for error message
        if (response.data.message) {
            $scope.error = response.data.message;
        }  else {
            $scope.user = response.data.user;
         }

    });
});

I have this factory which handles all the requests

angular.module('lastfm')

.factory('ajaxData', function ($http, $q) {

return {
    get: function (params) {
        return $http.get('http://ws.audioscrobbler.com/2.0/', {
            params : params
        });
    }
}

});
like image 229
Allan Avatar asked Nov 15 '13 02:11

Allan


1 Answers

Quite easy using $q.all(). $http itself returns a promise and $q.all() won't resolve until an array of promises are resolved

var ajax1=ajaxData.get(....).then(....);
var ajax2=ajaxData.get(....).then(....);

$q.all([ajax1,ajax2]).then(function(){
   /* all done, hide loader*/
})
like image 112
charlietfl Avatar answered Sep 23 '22 02:09

charlietfl