Injecting services in custom ErrorHandler causes "Cannot instantiate cyclic dependency!" error, how can I fix this?
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.