javascript - angularJS 1.0.x 中所有 http 请求的拦截器

标签 javascript angularjs interceptor

我目前在一个 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/

相关文章:

javascript - Ember 与服务同步循环

javascript - 递归 ngInclude

hadoop - 在发送到 channel 之前删除空的 Flume 事件

hibernate - 为什么使用 Hibernate Interceptor 的审计日志会在 SocketInputStream.socketRead0 处挂起?

javascript - 如何用我们自己的标签替换html标签

javascript - 未定义 forEach TypeError : undefined is not a function

javascript - 从指令生成的 html 范围内调用函数?

javascript - 无法从 AngularJS 中的元素计算 offsetHeight

jquery - 根据产品可用性禁用按钮

java - 如何从传出拦截器的消息中获取 REST 服务的响应负载?