2

What i want to do is this:

if im getting 401 response i want to intercept and send another post request to get new token from my server. but i cant do it in the angular interceptor. i get this error:

Circular dependency found: authService <- authIn <- $http <- $translateStaticFilesLoader

whats the problem, and how i can do what i want?

  return {
        'responseError': function(rejection) {
            if (rejection.status === 401) {
                authService.getNewToken();
                return $q.reject(rejection);
                }
                return $q.reject(rejection);
            }
        };
    }
3
  • Obviously, you have a circular dependency. Commented Oct 21, 2014 at 9:35
  • OK, but how i can do such thing? Commented Oct 21, 2014 at 9:39
  • you can use this gist.github.com/Mirodil/952e5932c284a2d205db Commented Aug 17, 2015 at 12:47

1 Answer 1

1

You can try to use $injector and make something like this:

$provide.factory('MyHttpInterceptor', ['$q', '$injector', function ($q, $injector) {
  return {
    responseError: function (rejection) {
      console.log("MyHttpInterceptor rejection ", rejection); // Contains the data from the first response.
      var $http = $injector.get('$http');
      // Return another $http call.
      return $http.get('http://ip.jsontest.com/');
    }
  };
}]);

The bad side of such solution is that you can get into infinite loop of $http calls. If your second $http request fails again and again you will always fire Interceptor. You should at least add check for status code like you have made it rejection.status === 401.

The working Plunker with super simple example.

Also you may look at this module https://github.com/witoldsz/angular-http-auth.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.