我仍在学习 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/