[英]Cyclic dependency issue in Angular2
I developed a custom error handler which implements Angular2 Error Handler class. 我开发了一个实现Angular2 Error Handler类的自定义错误处理程序。 My custom error handler uses a logger service to log errors. 我的自定义错误处理程序使用记录器服务记录错误。 The code looks like as follows: 该代码如下所示:
export class CustomErrorHandler implements ErrorHandler {
constructor(private logger: LoggerService) {}
handleError(error: any): void {
logger.error('....');
}
}
However, since the logger service uses Angular2 router, I cannot inject the logger service to the custom error handler! 但是,由于记录器服务使用Angular2路由器,因此无法将记录器服务注入自定义错误处理程序! Running the above code throws the following exception! 运行上面的代码将引发以下异常! Error: Provider parse errors:↵Cannot instantiate cyclic dependency!
You need to inject manually, to avoid the cyclic dependency problem because this class is created before the providers, your code should be: 您需要手动注入,以避免循环依赖问题,因为此类是在提供程序之前创建的,因此您的代码应为:
import { Injectable, Injector } from '@angular/core';
import { Logger } from '...';
@Injectable()
export class CustomErrorHandler implements ErrorHandler {
constructor(private injector: Injector) {}
handleError(error: any): void {
const logger = this.injector.get(Logger);
logger.error('....');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.