QuantumDream QuantumDream - 5 months ago 52
AngularJS Question

Angular $httpProvider Interceptor and $resource

I have a simple Interceptor in angular that intercepts requests and adds a authorization header. It also intercepts a response error of 401 to know if the request failed because of authorization.

Unfortunately it seems to mess with $resource, because my $resource calls ALWAYS return the success callback and never an error (be it 400 or 500 whatever).

It's definitly the interceptor, because if I remove it, the $resource calls return with the correct callback.

Any ideas on how to fix this behavior?

Here's the interceptors request:

function request(config) {
var token = 'whatever-my-token-is';

if (token) {
config.headers.authorization = token;
}

return config;
}


And the responseError:

function responseError(response) {
if (response.status === 401) {
$rootScope.$broadcast('unauthorized');
}

return response;
}


Any help appreciated

Answer

I think you need to use a promise to return the error.
adding $q to your Interceptor factory. like so

$provide.factory('MyHttpInterceptor', function ($q){
   ...
})

and then have the responseError()

function responseError(response) {
  if (response.status === 401) {
    $rootScope.$broadcast('unauthorized');
  }

 return $q.reject(response);
}

this link might help also https://djds4rce.wordpress.com/2013/08/13/understanding-angular-http-interceptors/