Inject $ state (ui-router) into $ http interceptor is causing circular dependency error, how to solve?

2

What do I need:

I need when the http request returns error 401 or 403 the user is redirected to login screen.

Problem:
The problem happens when I inject the $ state into my factory, it causes the circular dependency error:

  

Uncaught Error: [$ injector: cdep] Circular dependency found: $ http

asked by anonymous 03.02.2017 / 12:04

1 answer

2

To correct the problem, simply inject $state manually using the $injector service, below an example seen in a SoEn response :

var interceptor = ['$location', '$q', '$injector', function($location, $q, $injector) {
    function success(response) {
        return response;
    }

    function error(response) {

        if(response.status === 401 || response.status === 403) {
            $injector.get('$state').transitionTo('public.login');
            return $q.reject(response);
        }
        else {
            return $q.reject(response);
        }
    }

    return function(promise) {
        return promise.then(success, error);
    }
}];

$httpProvider.responseInterceptors.push(interceptor);

The problem occurs because angular-ui-route injects service $http as a dependency within $templateFactory , and this creates a circular reference for $ http with $httpProvider . So we have to do the injection manually.

This problem will also happen if you try to inject the $ http service, as exemplified in Jonathan Palumbo's answer:

var interceptor = ['$location', '$q', '$http', function($location, $q, $http) 
    
03.02.2017 / 12:13