问题描述
我目前一个角度应用程序工作在whcih我想写从我的应用程序的所有HTTP请求,轮流调用一个服务来了解会话的单点登录是否仍然有效与否,如果它不是一个拦截器活动I路由经过我的单点登录,然后服务于用户请求加载下一个页面或结果。我不知道如何在AngularJS写一个拦截器和不知道如何保存用户请求时,我重定向我的网页上的单点登录。
I am currently working in a angular app in whcih I wanted to write an interceptor for all http request from my app which in turns calls a service to know whether the single sign on session is still active or not, if it is not active I should route to my single sign on and then serves the user request to load the next page or results. I am not sure how to write a interceptor in AngularJS and not sure how to save the user request when I redirect my page to Single sign on.
我目前使用angularjs 1.0.2,我看到有在1.0.2文档responseInterceptors,但不requestInterceptors。 。有周围的工作写在角1.0.2 HTTP调用请求Interceptor
I am currently using angularjs 1.0.2 , I see that there are responseInterceptors in 1.0.2 documentation, but not requestInterceptors . . Is there a work around to write request Interceptors for http calls in Angular 1.0.2
推荐答案
有对当前稳定工作1.2.0的官方文档中的一个很好的例子。
There is a good example in the official documentation working for the current stable 1.2.0.
[。$ HTTP] [1](在页面顶部季度,搜索拦截)
[http://docs.angularjs.org/api/ng.$http][1] (top quarter of the page, search for Interceptors)
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。如果你把这个有一个全局运行的定时器,可以检测的最后一个请求多久以前了。
Instead of counting the pendingRequests, you can store the current time, lets say as lastRequestTimestamp. If you combine this with a globally running timer, you can detect how long ago the last request was.
这篇关于拦截器在angularJS 1.0.x的所有HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!