Angularjs多个ajax请求优化

All*_*lan 8 api ajax angularjs

我还在学习Angular JS并且让这个控制器使用不同的参数向lastfm api发出两个ajax请求.我想知道每个请求何时完成,以便我可以显示两个请求的加载指示器.我已经研究了它并阅读了有关承诺和$ q服务但是无法理解如何将其融入到这里.有没有更好的方法来设置它?以及如何知道每个请求何时完成.谢谢.

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

    });
});
Run Code Online (Sandbox Code Playgroud)

我有这个处理所有要求的工厂

angular.module('lastfm')

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

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

});
Run Code Online (Sandbox Code Playgroud)

cha*_*tfl 16

很容易使用$q.all().$http本身返回一个promise,$q.all()在解决一系列promises之前不会解决

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

$q.all([ajax1,ajax2]).then(function(){
   /* all done, hide loader*/
})
Run Code Online (Sandbox Code Playgroud)