ajax - Angularjs 多ajax请求优化

标签 ajax api angularjs

我仍在学习 Angular JS 并拥有这个 Controller ,它使用不同的参数向 lastfm api 发出两个 ajax 请求。我想知道每个请求何时完成,以便我可以为两个请求显示加载指示器。我已经研究过它并阅读了关于 promises 和 $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;
         }

    });
});

我有这个处理所有请求的工厂
angular.module('lastfm')

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

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

});

最佳答案

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

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

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

关于ajax - Angularjs 多ajax请求优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19992637/

相关文章:

javascript - 数组推送结果为空数组javascript

android - "ClassNotFoundException: Didn' t 在 API 19 上的路径 DexPathList 上找到类

javascript - 页面/表格加载动画

php - ajax php foreach循环在每次迭代后更新

javascript - jQuery:动画 Div 在 'Click' 上调整大小

javascript - HTML5 : Changing the value of items in localStorage

javascript - 如何在 ng-repeat angularJS 内的 $scope 中赋值

java - 从包含 TinyMCE (html) 内容的 JSON 对象生成 PDF

javascript - Google 更新和 AngularJS/JavaScript 网站

php - 错误处理 php_network_getaddresses : getaddrinfo failed. 如何处理?