I have an Angular app with a custom ErrorHandler
. My goal is to allow components (say, the AppComponent
) to be notified when a global error occurs so that they can present it in the interface. I implemented this by extending ErrorHandler
(as described in
My question
Why does the callback for the subscription in AppComponent
not occur?
This question seems related, but it doesn't have an accepted answer, and adding .asObservable()
before subscribing in the component doesn't resolve the problem. This question is also related and "solves" the problem by calling a method on an error reporting service explicitly in the error handler, but I'm still curious why my solution doesn't work.
My suspicion is that despite the fact that my ErrorHandlerService
is marked with providedIn: 'root'
, the framework creates an instance to act as the global error handler, and the AppComponent
is receiving a second one, but I can't find documentation about this behavior anywhere. Any help appreciated!
CodePudding user response:
Cool question, nicely formatted
tl;dr
//in app.component.ts
constructor(@Inject(ErrorHandler) private errorService: ErrorsService,
This is a (uncommon) dependancy injection problem
In your app.module.ts
you have
providers: [{ provide: ErrorHandler, useClass: ErrorsService }],
The token is ErrorHandler
, the provided thing is ErrorsService
When you inject a service in your constructor like
constructor(private errorService: ErrorsService
That's shorthand for
constructor(@Inject(ErrorsService) private errorService: ErrorsService
Here the token is ErrorsService
, the provided thing is ErrorsService
Angular looks for providers of tokens to fulfill the DI, so the fix is to use the right token.