我目前在一个 Angular 应用程序中工作,我想为来 self 的应用程序的所有 http 请求编写一个拦截器,然后调用一个服务来了解单点登录 session 是否仍然处于事件状态,如果不是active 我应该路由到我的单点登录,然后满足用户请求以加载下一页或结果。我不确定如何在 AngularJS 中编写拦截器,也不确定在将页面重定向到单点登录时如何保存用户请求。
我目前使用的是 angularjs 1.0.2 ,我看到 1.0.2 文档中有 responseInterceptors ,但没有 requestInterceptors 。 .是否有解决方法为 Angular 1.0.2 中的 http 调用编写请求拦截器
最佳答案
在当前稳定版 1.2.0 的官方文档中有一个很好的例子。
[ http://docs.angularjs.org/api/ng .$http][1](页面上四分之一,搜索拦截器)
angular.module('RequestInterceptor', [])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('requestInterceptor');
})
.factory('requestInterceptor', function ($q, $rootScope) {
$rootScope.pendingRequests = 0;
return {
'request': function (config) {
$rootScope.pendingRequests++;
return config || $q.when(config);
},
'requestError': function(rejection) {
$rootScope.pendingRequests--;
return $q.reject(rejection);
},
'response': function(response) {
$rootScope.pendingRequests--;
return response || $q.when(response);
},
'responseError': function(rejection) {
$rootScope.pendingRequests--;
return $q.reject(rejection);
}
}
});
您可以存储当前时间,而不是计算 pendingRequests,可以说是 lastRequestTimestamp。如果将其与全局运行的计时器结合使用,您可以检测到上次请求是在多长时间前。
关于javascript - angularJS 1.0.x 中所有 http 请求的拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20062493/