这个jsbin 项目将@DmitryEvseev 的答案带到下一步。它可以更好地控制哪些请求可用于触发“加载...”。
这些请求{ showLoader: true }
用于显示“正在加载...”面板。
HTML
<div ng-app="app">
<div ng-controller="spinnerController as vm">
<div ng-if="vm.isLoading()">Loading ...</div>
</div>
</div>
Javascript
angular
.module('app', [])
.config(config)
.factory('httpLoader', httpLoader)
.factory('httpLoaderInterceptor', httpLoaderInterceptor)
.controller('spinnerController', spinnerController);
function config($httpProvider) {
//adding the default http status code handler
$httpProvider.interceptors.push('httpLoaderInterceptor');
}
function httpLoader() {
var pendingReqs = {};
var factory = {
addPendingReq: addPendingReq,
subtractPendingReq: subtractPendingReq,
getPendingReqs: getPendingReqs
};
return factory;
function addPendingReq(url) {
console.log('adding url', url);
pendingReqs[url] = true;
}
function subtractPendingReq(url) {
console.log('removing url', url);
delete pendingReqs[url];
}
function getPendingReqs() {
return sizeOf(pendingReqs);
}
}
function httpLoaderInterceptor($q, httpLoader) {
var factory = {
request: request,
response: response,
responseError: responseError
};
return factory;
function request(config) {
console.log('request', config.url);
if (config.showLoader) {
httpLoader.addPendingReq(config.url);
}
return config;
}
function response(res) {
console.log('response', res.config.url);
if (res.config.showLoader) {
httpLoader.subtractPendingReq(res.config.url);
}
}
function responseError(res) {
console.log('responseError', res.config.url);
if (res.config.showLoader) {
httpLoader.subtractPendingReq(res.config.url);
}
return $q.reject(res);
}
}
function spinnerController($http, httpLoader) {
var self = this;
self.isLoading = function() {
return httpLoader.getPendingReqs() > 0;
};
$http.get('http://stackoverflow.com/posts/34561385',{
showLoader: true
});
$http.get('http://www.amazon.com', {
showLoader: true
});
$http.get('http://www.yahoo.com',{
showLoader: true
});
$http.get('http://www.stackoverflow.com',{
showLoader: true
});
}
function sizeOf(obj) {
var size = 0,
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
}