I have the following code :
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)
}
}
However, when my app bootstrap, it fails if I have an injection in MyErrorHandler
with the following error :
Unhandled Promise rejection: Provider parse errors:
Cannot instantiate cyclic dependency!
If I do remove constructor (private _appLog: AppLog) {}
and then do something else in handleError
it works just fine and the ErrorHandler is called.
I guess it doesn't work as AppLog and MyErrorHandler are instantiated at the same time
You can use this workaround to break up cyclic dependencies with DI
@Injectable()
export class MyErrorHandler implements ErrorHandler {
private _appLog: AppLog;
constructor (injector:Injector) {
setTimeout(() => this._appLog = injector.get(AppLog));
}
...
}
Angulars DI itself just doesn't support cyclic dependencies.
The ErrorHandler is created before the providers. So we need Injector for dependency injection in our custom error handler class.
@Injectable()
export class MyErrorHandler implements ErrorHandler{
constructor(private injector: Injector) { }
handleError(error: any) {
let router = this.injector.get(ServiceName);
}
}
Create a default service via Angular cli and check the first part see providedIn: 'root',
@Injectable({
providedIn: 'root',
})
export class CustomService{
constructor(private otherService: OtherService) { // ok not failed }
}
For more detail check angular @Injectable-level configuration
@NgModule-level injectors You can configure a provider at the module level using the providers metadata option for a non-root NgModule, in order to limit the scope of the provider to that module. This is the equivalent of specifying the non-root module in the @Injectable() metadata, except that the service provided via providers is not tree-shakable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With