Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS circular dependency issue with $http

Tags:

angularjs

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!

like image 239
Jakobovski Avatar asked Aug 04 '14 19:08

Jakobovski


1 Answers

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) => {
        ...
      }
    };
  })
 ;
like image 118
snrbrnjna Avatar answered Nov 10 '22 09:11

snrbrnjna