2

Due to John Papa - 10 AngularJS Patterns presentation advices I try to implement additional functionality to exception handling:

exceptionHandlerDecorator.$inject = ['$provide'];
function exceptionHandlerDecorator($provide){
    $provide.decorator('$exceptionHandler', handleException);
}

handleException.$inject = ['$delegate', 'ExceptionHandlerService'];

function handleException($delegate, ExceptionHandlerService){
    function handle(exception, cause){
        $delegate(exception, cause);
        ExceptionHandlerService.handle(exception.message);
    }

    return handle;
}

ExceptionHandlerService.$inject = ['$modal'];

function ExceptionHandlerService($modal){
    //do things
}

But when I try ti inject $modal to ExceptionHandlerService from Angular UI Bootstrap I got Error: $injector:cdep Circular Dependency which terrified me. I tried to use accepted solution from very similar question, Injecting $http into angular factory($exceptionHandler) results in a Circular dependency:

function ExceptionHandlerService($window, $injector){
    var $modal = $injector.get('$modal')
}

But it gave me exactly the same result - Error: $injector:cdep Circular Dependency. Has anyone had similar problem and knows the solution? Thank you in advance for your attention.

Community
  • 1
  • 1
Radek Anuszewski
  • 1,812
  • 8
  • 34
  • 62

1 Answers1

2

The issue is that even if you do,

function ExceptionHandlerService($window, $injector){
    var $modal = $injector.get('$modal')
}

It will try to instantiate $modal service as the ExceptionHandlerService is instantiated via decorator, so it will cause cDep error. You would want to instead get the $modal instance lazily when needed and must not try to instantiate it (or get it) during the service instantiation process. i.e:

 function ExceptionHandlerService($window, $injector){

        function _getModal(){
           //You can afford to do this everytme as service is a singleton and
           //the IOC container will have this instance always once instantiated as it will just act asa getter.
           return $injector.get('$modal');
        }

        function logStuff(){
            _getModal().modal(....
        }
    }
PSL
  • 123,204
  • 21
  • 253
  • 243