3
votes

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

2
Please include the code of what you have already tried. We can’t guess what’s your current implementation to figure out the errorHugo Noro
i recoomend you to use stackblitz.com for demostration of your isuuehappyZZR1400
Please include your code on the question itself. Using images is a bad idea since the website could no longer exist, your question can't be searchable since images aren't text and those with poor internet will have to wait for a while just to load the image.Edric
Thanks for adding your solution. Instead of editing your question, just post it as an answer and mark it as a solution. This way other users will know that your question was resolved.Kim Kern

2 Answers

4
votes

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

3
votes

In my case, The solution was using this.handleError.bind(this) as shown below:

  public post<T>(url: string, data: any, options?: HttpOptions): Observable<T> {
    return this.http.post<T>(this.baseUrl + url, data, options).pipe(
      map((res: T) => {
        return res as T;
      }),
      catchError(this.handleError.bind(this))
    );