用于angularJS 1.0.x中所有http请求的拦截器

时间:2013-11-19 03:20:14

标签: javascript angularjs interceptor

我目前正在使用一个有角度的应用程序,因为我想从我的应用程序中为所有http请求编写一个拦截器,该请求依次调用服务来了解会话中的单点登录是否仍处于活动状态,如果不是我应该路由到我的单点登录,然后提供用户请求加载下一页或结果。我不确定如何在AngularJS中编写拦截器,并且在我将页面重定向到单点登录时不确定如何保存用户请求。

我目前正在使用angularjs 1.0.2,我看到1.0.2文档中有responseInterceptors,但不是requestInterceptors。 。是否有工作为Angular 1.0.2中的http调用编写请求拦截器

2 个答案:

答案 0 :(得分:6)

在为当前稳定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。如果将其与全局运行的计时器结合使用,则可以检测上次请求的持续时间。

答案 1 :(得分:5)

您可以非常轻松地使用拦截器

这是一个示例

var mydevices = angular.module('deviceDetails', ['ui.bootstrap', 'tags-input'])

mydevices.config(function ($httpProvider) {
$httpProvider.interceptors.push(function($q) {
      return {
       'request': function(config) {
           if (config.method === 'GET' && config.url.contains("/rest/")) {
               var sep = config.url.indexOf('?') === -1 ? '?' : '&';
               config.url = config.url + sep + 'cacheSlayer=' + new Date().getTime();
           }
           console.log(config.url);
           return config || $q.when(config);
        }
      };
    });
});

上面的示例修改了所有/ rest / URLs

的网址

希望这有帮助