2014-01-10 62 views
11

一些请求下面是我拦截它处理全局错误。但我想绕过一些http请求。有什么建议么 ?AngularJs:排除从拦截

var interceptor = ['$rootScope', '$q',function (scope, $q) { 
     function success(response) { 
      return response; 
     } 
     function error(response) { 
      var status = response.status; 
      if (status == 401) { 
       window.location = "./index.html#/404"; 
       return; 
      } 
      if (status == 0) { 
       window.location = "./index.html#/nointernet"; 
      } 
      return $q.reject(response); 
     } 
     return function (promise) { 
      return promise.then(success, error); 
     } 
    }]; 
    $httpProvider.responseInterceptors.push(interceptor); 

回答

27

我能够通过添加属性到$ http请求的配置对象只是实现这个功能。即。 ignore401。然后,在我的拦截器,在响应错误处理程序,检查的配置对象的属性,如果它存在,不转发登录或任何其他你在一个401响应做。

首先,拦截器:

$provide.factory('authorization', function() { 
    return { 
     ... 

     responseError: (rejection) => { 
      if (rejection.status === 401 && !rejection.config.ignore401) { 
       // redirect to login 
      } 

      return $q.reject(rejection); 
     } 
    }; 
}); 

然后,我想绕过401错误处理程序的任何请求:

$http({ 
    method: 'GET', 
    url: '/example/request/to/ignore/401error', 
    ignore401: true 
}); 

希望有所帮助。

+1

应该有接受的答案 –

+0

但没有肯定,要求增加“自定义”属性配置对象仍然是可用的响应,是什么吗? – cipak

0

响应对象是否包含“options”属性,您可以在其中检查请求中使用了哪个URL?

1

我解决这个如下:

$httpProvider.interceptors.push(function($rootScope) { 
    return { 
     request: function(config) { 
     var hideUrl = "benefit/getall"; // don't show the loading indicator for this request 
     var hide = (config.url.indexOf(hideUrl)); // is this isn't -1, it means we should hide the request from the loading indicator 
     if(hide == -1) 
     { 
      $rootScope.$broadcast('loading:show') 

     } 
     return config 
     }, 
     response: function(response) { 
     $rootScope.$broadcast('loading:hide') 
     return response 
     } 
    } 
    });