2

由於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 
} 

但是當我嘗試TI從角UI注入$modalExceptionHandlerService Bootstrap我得到了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

當你嘗試解決方案時,你是否刪除了行'ExceptionHandlerService。$ inject = ['$ modal'];'? – Ian

+0

@Ian是的,我刪除了這一行 –

回答

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

您的解決方案非常完美 - 非常感謝您! –