I'm fairly new to Angular 2+, so please bear with me if I'm way off. My goal is to have a shared notification service to be used throughout the application. For the most part, I got it working fine. It is a lazy module structure, so in order to not have issues with multiple instances (took me a while to figure this one out) I had to add a forRoot() method to my SharedModule class as such:
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
NotificationService,
{
provide: ErrorHandler,
useClass: ErrorHandlerService
}]
};
}
}
Then, the SharedModule is added to the AppModule calling forRoot():
@NgModule({
declarations: [...],
imports: [
...
SharedModule.forRoot()
...
],
providers: [...],
bootstrap: [...]
})
export class AppModule { }
I was happy to see that the notification service worked fine from my lazy modules by simply adding SharedModule to the lazy loaded module and then making notificationService calls from the components.
The problem is with the global error handler (provided in the forRoot() in SharedModule, see above), it looks like it might be creating a second instance of notification service and it doesn't work properly.
I guess first of all, am I structuring this correctly? If so, what am I doing wrong so that the notification service acts weird?
Here's the code for the error handler service:
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { NotificationService } from './notification.service';
@Injectable()
export class ErrorHandlerService implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error: Error) {
const notificationService = this.injector.get(NotificationService);
const router = this.injector.get(Router);
if (error instanceof HttpErrorResponse) {
if (!navigator.onLine) {
} else {
console.log('Http error!');
notificationService.error('Error!', error.message);
}
} else {
}
console.error('It happens: ', error);
}
}
Again, calling notification service from components works fine, the behavior is completely different when calling from the error handler service. The behavior I get is similar to the one I was getting from components BEFORE adding the forRoot() method to the SharedModule module, thus the theory of multiple instances.
Any help appreciated. Thanks
--- EDIT ---
I've created Stackblitz to show the different behavior when calling notification service from a component vs from the error handler service. The show notification button shows the notification as intended, but when making an error http call, notice that the first time you click, the notification doesn't show, and if keep playing with it, it will sometimes go away all of the sudden, or not go away at all, whereas you cannot make the same happen when using the show notification button.