QuantumDream
QuantumDream

Reputation: 137

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

Upvotes: 1

Views: 271

Answers (1)

Michael
Michael

Reputation: 653

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/

Upvotes: 0

Related Questions