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!

Community
  • 1
  • 1
Jakobovski
  • 3,203
  • 1
  • 31
  • 38
  • 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 – Roman Kolpak Aug 04 '14 at 19:13
  • I wonder if you could do an $emit or $broadcast in the interceptor, just a thought. – Alex C Aug 04 '14 at 19:14
  • Have you tried this approach:http://stackoverflow.com/a/19954545/2407203 ? – Norbor Illig Feb 11 '15 at 12:33

1 Answers1

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) => {
        ...
      }
    };
  })
 ;
Community
  • 1
  • 1
snrbrnjna
  • 81
  • 1
  • 2
  • this doesnt work for me, I still get cd error (I have my own service in my interceptor, which itself depends on $http) – felixfbecker Jun 17 '15 at 13:58
  • 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. – George Kagan Oct 08 '15 at 08:18