我有以下代码:
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
了以下错误,则会失败:
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本身不支持循环依赖.