这个
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) {
$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;
}
$httpProvider
。我也认为它很复杂,但恐怕你必须咬紧牙关。 - Andriy Drozdyuk