由于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
。有谁有类似的问题,知道解决方案吗?提前感谢您的关注。
答案 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(....
}
}