AngularJS 1.1.5(这被认为是不稳定的版本)提供了对请求和响应拦截器的支持。这些概念与通过 angular-http-auth 拦截器模块( https://github.com/witoldsz/angular-http-auth)所做的非常相似
可以将以下 http-throttler 服务注入您的代码以限制您的 HTTP 请求。当你定义你的应用程序时,将它连接到 Angular 中。
例子:
angular.module('myApp', ['http-throttler'])
.config(['$routeProvider','$httpProvider', function($routeProvider, $httpProvider) {
$httpProvider.interceptors.push('httpThrottler');
$routeProvider.
when('.............your stuff here..........')
...........more of your stuff....
});
将其放入 http-interceptor.js 并将其包含在您的应用程序中。
(function() {
"use strict"; angular.module('http-throttler', ['http-interceptor-buffer']).factory("httpThrottler", ['$q', '$log', 'httpBuffer', function($q, $log, httpBuffer) {
var reqCount, service;
reqCount = 0;
service = {
request: function(config) {
var deferred;
$log.info("Incoming Request - current count = " + reqCount);
if (reqCount >= 10) {
$log.warn("Too many requests");
deferred = $q.defer();
httpBuffer.append(config, deferred);
return deferred.promise;
} else {
reqCount++;
return config || $q.when(config);
}
},
response: function(response) {
$log.info("Response received from server");
reqCount--;
httpBuffer.retryOne();
return response || $q.when(response);
}
};
return service;
}
]);
angular.module('http-interceptor-buffer', []).factory('httpBuffer', [
'$log', function($log) {
var buffer, retryHttpRequest, service;
buffer = [];
retryHttpRequest = function(config, deferred) {
if (config != null) {
$log.info("Resolving config promise");
return deferred.resolve(config);
}
};
service = {
append: function(config, deferred) {
return buffer.push({
config: config,
deferred: deferred
});
},
retryOne: function() {
var req;
if (buffer.length > 0) {
req = buffer.pop();
return retryHttpRequest(req.config, req.deferred);
}
}
};
return service;
}
]);
}).call(this);
上面,每个问题都硬编码为 10。如果其他人发现它有用,我可能会将其配置并推送到 GitHub 上。
再说一遍——这在 AngularJS 的 1.0.7 版本中不起作用,因为 1.0.7 不支持 $httpProvider 上的新拦截器数组。它只支持 responseInterceptors。我没有尝试过 1.1.4,但这似乎在 1.1.5 中运行良好。
代码可在 GitHub @ https://github.com/mikepugh/angular-http-throttler