我有以下代码:
app.module.ts:
NgModule({
declarations: [
AppComponent
],
imports: [
RouterModule,
BrowserModule,
ReactiveFormsModule,
FormsModule,
HttpModule,
AppRoutingModule // Routes
],
providers: [ // services
AppLog,
{provide: ErrorHandler, useClass: MyErrorHandler}
],
bootstrap: [AppComponent]
})
export class AppModule {}
MyErrorHandler.ts:
@Injectable()
export class MyErrorHandler implements ErrorHandler {
constructor (private _appLog: AppLog) {}
handleError(error:any):void {
let errorMessage: string = "" + error
this._appLog.logMessageAsJson(errorMessage, "error")
.subscribe(
...
)
}
}
appLog.ts
@Injectable()
export class AppLog {
constructor (private _http: Http) {}
logMessageAsJson(message: string, type: string) {
let headers = new Headers({ "Content-Type": "application/json" })
let jsonMessage = {"type": type, "message": message}
return this._http.post(JSON.stringify(jsonMessage), headers)
}
}
但是,当我的应用程序启动时,如果我在
MyErrorHandler
中注入(inject)了以下错误,它将失败:Unhandled Promise rejection: Provider parse errors:
Cannot instantiate cyclic dependency!
如果我确实删除了
constructor (private _appLog: AppLog) {}
,然后在handleError
中执行了其他操作,则它可以正常工作,并调用ErrorHandler。我猜这不起作用,因为同时实例化了AppLog和MyErrorHandler
最佳答案
您可以使用此替代方法来解决与DI的循环依赖性
@Injectable()
export class MyErrorHandler implements ErrorHandler {
private _appLog: AppLog;
constructor (injector:Injector) {
setTimeout(() => this._appLog = injector.get(AppLog));
}
...
}
Angulars DI本身只是不支持循环依赖性。
关于angular - 在自定义ErrorHandler中注入(inject)服务会导致 “Cannot instantiate cyclic dependency!”错误,如何解决此问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41585863/