Angular - 尝试将 $modal 注入异常处理程序装饰器时的循环依赖注入器

Angular - circular dependency injector whie trying inject $modal to exception handler decorator

由于 John Papa - 10 AngularJS Patterns presentation 建议,我尝试实现异常处理的附加功能:

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
}

但是当我尝试从 Angular UI Bootstrap 注入 $modalExceptionHandlerService 时,我得到了 Error: $injector:cdep Circular Dependency which terrified me. I tried to use accepted solution from very similar question, :

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

但它给了我完全相同的结果 - Error: $injector:cdep Circular Dependency。有没有人遇到过类似的问题并且知道解决方案?预先感谢您的关注。

问题是即使你这样做了,

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

它将尝试实例化 $modal 服务,因为 ExceptionHandlerService 是通过装饰器实例化的,因此会导致 cDep 错误。您可能希望在需要时延迟获取 $modal 实例,并且 不得在服务实例化过程中尝试实例化(或获取)实例 。即:

 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(....
        }
    }