Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
    
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 –  rawry Aug 4 '14 at 19:13
    
I wonder if you could do an $emit or $broadcast in the interceptor, just a thought. –  Alex C Aug 4 '14 at 19:14
    
Have you tried this approach:stackoverflow.com/a/19954545/2407203 ? –  Norbor Illig Feb 11 at 12:33

1 Answer 1

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) => {
        ...
      }
    };
  })
 ;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.