5

I am having an issue with circular dependancy. I built a $http interceptor to handle all $http errors and alert the user with a modal(Angular UI-Bootstrap).

The dependency chain looks like this:

$http <- $modal <- ErrorHandlerService <- HTTPErrorInterceptorService <- $http

The error I am getting is:

Uncaught Error: [$injector:cdep] Circular dependency found: $http <- $modal <- ErrorHandlerService <- HTTPErrorInterceptorService <- $http <- $templateFactory <- $view <- $state

I have read that the trick to getting around these types of issues is to use $injector. I have tried using $injector to inject $modal, I have tried using $injector to inject ErrorHandlerService but I am still getting the Circular dependency error.

Does anybody have any ideas how to get around this?

Thanks!

3
  • It seems that anything that depends on $http service cannot be injected into a $http interceptor. I haven't find any way to workaround this, just avoid using $http-dependant stuff in interceptors Commented Aug 4, 2014 at 19:13
  • I wonder if you could do an $emit or $broadcast in the interceptor, just a thought. Commented Aug 4, 2014 at 19:14
  • Have you tried this approach:stackoverflow.com/a/19954545/2407203 ? Commented Feb 11, 2015 at 12:33

1 Answer 1

8

The important point of the trick in the mentioned question is, that you resolve the dependency to $modal during the runtime of the interceptor, not in the factory.

This will work

angular.module('app')
  .factory('httpAuthInterceptor', function($q, $injector) {
    let $modal;  
    return {
      responseError: (rejection) => {
        if (rejection.status === 401) {
          $modal = $modal || $injector.get('$modal');
          $modal.open({
            template: 'not logged in'
          });
        }
        return $q.reject(rejection);
      }
    };
  })
;

This will NOT work

angular.module('app')
  .factory('httpAuthInterceptor', function($q, $injector) {
    let $modal = $injector.get('$modal');  
    return {
      responseError: (rejection) => {
        ...
      }
    };
  })
 ;
Sign up to request clarification or add additional context in comments.

2 Comments

this doesnt work for me, I still get cd error (I have my own service in my interceptor, which itself depends on $http)
Works for me. @freshfelicio Loading your own service via $injector at run-time should solve the issue, since you clearly have CD due to the HTTP interceptor depending on $http.

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.