javascript - Angular - 循环依赖注入(inject)器尝试将 $modal 注入(inject)异常处理程序装饰器

标签 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 注入(inject) $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')
}

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

最佳答案

问题是,即使你这样做,

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

关于javascript - Angular - 循环依赖注入(inject)器尝试将 $modal 注入(inject)异常处理程序装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33463300/

相关文章:

javascript - 在 ng-click 中设置 angularjs 数据

javascript - 以 Angular 2 设置路线

javascript - AngularJS 中的混​​合内容

c# - Unity、RegisterType<> 和 Singleton 对象

javascript - 如何使用 Three.js 在点击到达特定位置后停止相机动画

javascript - 缩放 HTML Canvas 元素

javascript - 如何在chrome开发者工具中添加伪元素?

java - 打破循环依赖以使用依赖注入(inject)

C# 依赖注入(inject)框架

javascript - Google 表格中的 Unpivot - 多个标题列和行