8

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

});

1 Answer 1

16

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*/
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.