前端之家收集整理的这篇文章主要介绍了
AngularJS循环依赖,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
301_0@
我正在做一个记录器服务,通过将
错误(或调试如果启用)扩展到indexedDB
数据库来扩展角度的$log服务.以下是
代码:
angular.module('appLogger',['appDatabase'])
.service('LogServices',function($log,Database) {
// ...
this.log = function(type,message,details) {
var log = {};
log.type = type
log.context = this.context;
log.message = message;
log.dateTime = moment().format('YYYY-MM-DD HH:mm:ss');
log.details = details || '';
$log[type.toLowerCase()](log);
if (type === 'ERROR' || this.logDebug) {
Database.logSave(log);
}
};
// ...
})
这是按照预期在我的服务中工作.现在问题是我不能在数据库服务中使用我的记录器,因为它抛出一个循环依赖错误.我明白问题,但我不知道该怎么解决呢?我该怎么解决?
感谢您的帮助:-)
Angular抱怨循环依赖的原因是…有一个.
这是一条非常危险的路径,但如果你知道你在做什么(最后一个字),那么有一个
解决方案来规避:
.service('LogServices',$injector) {
// ...
var Database; // Will initialize it later
this.log = function(type,details) {
/* Before using Database for the first time
* we need to inject it */
if (!Database) { Database = $injector.get('Database'); }
var log = {};
log.type = type
log.context = this.context;
log.message = message;
log.dateTime = moment().format('YYYY-MM-DD HH:mm:ss');
log.details = details || '';
$log[type.toLowerCase()](log);
if (type === 'ERROR' || this.logDebug) {
Database.logSave(log);
}
};
// ...
})
另见这个short demo.