我目前在一个有角度的应用程序中工作,我想为我的应用程序中的所有http请求编写一个拦截器,这反过来会调用一个服务,以了解单点登录会话是否仍处于活动状态,如果未处于活动状态,我应该转到我的单点登录,然后根据用户请求加载下一页或结果。我不确定如何在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); } } });
您可以存储当前时间,而不用计算未决请求,可以说为lastRequestTimestamp。如果将其与全局运行的计时器结合使用,则可以检测到上一个请求是多久之前的。