由于 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) $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')
}
但它给了我完全相同的结果 - 错误:$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/