【问题标题】:Angular - circular dependency injector whie trying inject $modal to exception handler decoratorAngular - 循环依赖注入器尝试将 $modal 注入异常处理程序装饰器
【发布时间】:2016-02-01 11:47:18
【问题描述】:

由于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 注入 $modal 到 ExceptionHandlerService 时,我得到了 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。有没有人遇到过类似的问题并知道解决方案?提前感谢您的关注。

【问题讨论】:

  • 当您尝试解决方案时,您是否删除了 ExceptionHandlerService.$inject = ['$modal']; 行?
  • @Ian 是的,我删除了这一行

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


【解决方案1】:

问题是,即使你这样做了,

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

【讨论】:

    猜你喜欢
    • 2016-10-20
    • 2017-02-05
    • 2018-08-07
    • 2021-07-13
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多