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

时间:2015-11-01 14:35:31

标签: javascript angularjs dependency-injection angular-ui angularjs-service

由于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,这吓坏了我。我尝试使用来自非常相似的问题Injecting $http into angular factory($exceptionHandler) results in a Circular dependency

的公认解决方案
function ExceptionHandlerService($window, $injector){
    var $modal = $injector.get('$modal')
}

但它给了我完全相同的结果 - Error: $injector:cdep Circular Dependency。有谁有类似的问题,知道解决方案吗?提前感谢您的关注。

1 个答案:

答案 0 :(得分:2)

问题是,即使你这样做,

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