AngularJs:从Interceptor中排除一些请求

时间:2014-01-10 05:28:01

标签: javascript angularjs

下面是处理全局错误的拦截器。但我想绕过一些http请求。有什么建议吗?

 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);

3 个答案:

答案 0 :(得分:30)

我只需在$ http请求的config对象中添加一个属性即可实现此功能。即。 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 :(得分:2)

我解决这个问题如下:

$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
      }
    }
  });

答案 2 :(得分:0)

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