Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material SnackBar and custom ErrorHandler to notify error

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

like image 873
70X Avatar asked Oct 14 '25 03:10

70X


1 Answers

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

like image 67
70X Avatar answered Oct 17 '25 20:10

70X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!