[英]Injecting $http into angular factory($exceptionHandler) results in a Circular dependency
当我尝试将$ http注入到重写的工厂时,我得到错误:
未捕获错误:[$ injector:cdep]找到循环依赖项:$ http < - $ exceptionHandler < - $ rootScope
AngularModule.factory('$exceptionHandler', function ($http) {
任何想法如何解决? 如果我使用[]注入,$ http是未定义的
edit_ _ __ _ __ _ __ _ __ _ __ _ _
根据下面的答案,我试过:
MyModule.config(function($provide, $http) {
$provide.decorator("$exceptionHandler", function($delegate) {
return function(exception, cause) {..
但我仍然得到循环错误:
未捕获错误:[$ injector:cdep]找到循环依赖项:$ http < - $ exceptionHandler < - $ rootScope
注入$injector
,然后从那里获取$http
服务。 像这样的东西:
AngularModule.factory('$exceptionHandler', function ($injector) {
var $http = $injector.get("$http");
请参阅https://groups.google.com/forum/#!topic/angular/lbFY_14ZtnU/discussion
但是,这将完全覆盖Angular提供的$exceptionHandler
功能。 如果您只想将服务器端日志添加到现有功能,请参阅有关扩充$exceptionHandler
功能的此问题 。
我正在使用此解决方案,因为rootScope存在循环依赖问题:
angular
.module('facilityLog')
.provider('$exceptionHandler', function() {
"use strict";
this.$get = function($injector) {
function exceptionHandler(exception, cause) {
// This is the part where you get the instance of $http in your case
var $rootScope = $injector.get('$rootScope');
//...
}
return exceptionHandler;
}});
因此,如果您在exceptionHandler-Function中请求实例,则不会获得循环依赖性错误。
我使用以下来解决这个问题。 注意如何使用数组符号来使这种缩小安全。 另请注意,我完全覆盖$ esceptionHandler并使用我自己的服务来替换它。
angular
.module('app')
.factory('$exceptionHandler', $exceptionHandler);
$exceptionHandler.$inject = ['$injector', 'exceptionLoggingService'];
function $exceptionHandler($injector, exceptionLoggingService)
{
return function(exception, cause)
{
exceptionLoggingService.http = exceptionLoggingService.http || $injector.get('$http');
exceptionLoggingService.error(exception, cause);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.