Angular JS resolves circular dependency

I am trying to make an http.post call in a http interceptor but I am getting

Circular dependency found: $http <- Ace <- authInterceptor <- $http <- $templateRequest <- $compile

      

I understand why, but I don't know how to solve it ... Still new to angular and a little confused, I hope you can help me :) Heres is my code:

var app = angular.module('AceAngularApi', []);

app.service('Ace', ['$http', '$q', '$injector', '$window', function($http, $q, $injector, $window) {

    var user = null;

    var getCurrentUser = function() {
        var url = "http://localhost:8080/api/currentuser";

        var response = $http.post(url, {}).then(function(response) {});
        return response;
    };
    return {
        getCurrentUser: getCurrentUser,
    }
}]);

app.factory('authInterceptor', ['$rootScope', '$q', '$window', '$injector', 'Ace',
    function($rootScope, $q, $window, $injector, Ace) {
        return {
            request: function(config) {
                config.headers = config.headers || {};
                if ($window.localStorage.token) {
                    config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
                }
                return config;
            },
            response: function(response) {
                if (response.status === 401) {
                    // handle the case where the user is not authenticated
                } else {
                    Ace.getCurrentUser().then(function() {
                        console.log("Got current user");
                    });
                }
                return response || $q.when(response);
            }
        };
    }
]);

app.config(function($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
});

      

+3


source to share


1 answer


You are trying to define preprocessing functionality $http

by typing authInterceptor

in $httpProvider

, however authInterceptor

has a dependency on $http

, this leads to the circular dependency issue.

To work around this circular dependency issue, you can use a service $injector

to connectAce



app.factory('authInterceptor', ['$rootScope', '$q', '$window', '$injector',
function($rootScope, $q, $window, $injector) {
    return {
        response: function(response) {
            if (response.status === 401) {
                // handle the case where the user is not authenticated
            } else {
                var Ace = $injector.get('Ace');
                Ace.getCurrentUser().then(function() {
                    console.log("Got current user");
                });
            }
            return response || $q.when(response);
        }
    };
  }
]);

      

Another workaround is to register the interceptor in the run () block instead of the config () block, but keep in mind that run()

any call $http

has nothing to do withauthInterceptor

+8


source







All Articles