Angular Material SnackBar and custom ErrorHandler to notify error

70X picture 70X · Mar 25, 2018 · Viewed 7.5k times · Source

I have an error custom handler class that implements ErrorHandler of Angular 5 core. If an error occours, handleError method have to notify it sending a snackbar material component that show up. If the error is thrown in a test button, all be fine.

If the error occours on the method ngOnInit, the snackbar doesn't work properly and it show up in a position wrong of the page and you can't dismiss it anymore.

I.E.

My Component:

export class RootPageComponent implements OnInit {

    constructor() {}

    public buttonTest() {
        it.happens;
    }
    ngOnInit() {
        it.happens;
    }
}

This is my custom error handler:

export class ErrorHandlerCustom extends ErrorHandler {

    constructor(...){}
    handleError() {
        const notificationService = this.injector.get(NotificationService);
        // notification custom using snackbar material
        notificationService.exceptionError(error);
    }
}

Results with error in ngOnInit: ngOnInit error

Click on test button: click on test button

Answer

70X picture 70X · Mar 26, 2018

I have finally figured out the problem. I don't know if this is the correct way.

In a lot of cases the error handler will run outside of Angular's zone. This causes toasts not to behave correctly since change detection doesn't run on it. So it is necessary to use zone in properly run.


    this.zone.run(() => {
        this.snackBar.open(message, "UNDO");
    }

Here I found my solution and I post it just in case someone else encountered the same problem: https://github.com/angular/material2/issues/9875