2015-08-25 25 views
2

我想發佈在角度應用程序內發生的錯誤。

我按照在related question中給出的方法,正如答案中所建議的,我注入$注入器,然後從那裏獲得$ http服務。 但是該行

Uncaught Error: Circular dependency: $http <- $exceptionHandler <- $rootScope

不停地來。

here is the fiddle with the problem

與相關的代碼:

var mod = angular.module('test', []); 
mod.config(function ($provide) { 
    $provide.decorator("$exceptionHandler", ['$delegate', '$injector',    function ($delegate, $injector) { 
     var $http = $injector.get("$http"); 
    }]); 
    }); 
mod.controller('testCtrl', function ($scope) { 
    }); 

如果你對此有何評論線

var $http = $injector.get("$http");

循環依賴錯誤消失。

我想我錯過了我的理解。我究竟做錯了什麼?畢竟,這似乎爲別人工作。

任何關於如何實現「將錯誤發佈到服務」的初始目標的建議也受到歡迎。

謝謝大家

回答

3

功能

var mod = angular.module('test', []); 
mod.config(function ($provide) { 
    $provide.decorator("$exceptionHandler", ['$delegate', '$injector',function ($delegate, $injector) { 
      return function (exception, cause) { 
       var $http = $injector.get("$http"); 
      } 
    }]); 
    }); 

    mod.controller('testCtrl', function ($scope) { 
    }); 
+0

葉氏,使得它。非常感謝你。你有這種行爲的解釋嗎? –

2

你可以這樣做內包裝你的噴油器的代碼。

這將打破你的循環依賴錯誤,你也可以實現你的目標。

如果我沒有錯,那麼你只是想在異常處理程序中調用web服務。

var httpCallOnAngularError = angular.module('exceptionTestApp', []); 

/*httpCallOnAngularError.factory('$exceptionHandler', function() { 
return function (exception, cause) { 
     alert(exception.message); 
    }; 
});*/ 

httpCallOnAngularError.config(function ($provide) { 
    $provide.decorator("$exceptionHandler", function ($delegate, $injector) { 
     return function (exception, cause) { 
      var $rootScope = $injector.get('$rootScope'); 
      $delegate(exception, cause); 
      $rootScope.logAngularError(); 
      alert(exception.message); 
     }; 
    }); 
}); 
httpCallOnAngularError.run(function ($http, $rootScope) { 
    $rootScope.logAngularError = function() { 
     //Call your webservice here. 
     $http.get("http://jsonplaceholder.typicode.com/posts/1") 
       .success(function (response) { 
        console.log(JSON.stringify(response)); 
       }); 
    }; 

}); 

httpCallOnAngularError.controller('exceptionTestCtrl', function ($scope) { 
    throw {message: 'Log this error by calling webservice.'}; 
}); 

您可以通過此模板進行驗證。

<div ng-app="exceptionTestApp" ng-controller="exceptionTestCtrl"> 
</div> 

Webservice call in Exception Handler $http in $exceptionHandler

+0

謝謝薩蒂揚爲您提供的幫助。您的代碼似乎與爲@maddygoround工作的原因相同:$ injector的引用位於函數內部。我不明白爲什麼碰巧在這裏工作,而不是當$ injector在返回的函數之外。註冊裝飾器時是否有某種事件監聽器?你有解釋嗎? –