I developed a custom error handler which implements Angular2 Error Handler class. 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! Running the above code throws the following exception!
Error: Provider parse errors:↵Cannot instantiate cyclic dependency!
答案 0 :(得分:1)
你需要手动注入,以避免循环依赖问题,因为这个类是在提供者之前创建的,你的代码应该是:
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('....');
}
}