简体   繁体   English

角材料SnackBar和自定义ErrorHandler通知错误

[英]Angular Material SnackBar and custom ErrorHandler to notify error

I have an error custom handler class that implements ErrorHandler of Angular 5 core. 我有一个错误自定义处理程序类,该类实现Angular 5核心的ErrorHandler。 If an error occours, handleError method have to notify it sending a snackbar material component that show up. 如果发生错误,handleError方法必须通知它发送显示的小吃栏材料组件。 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. 如果错误发生在方法ngOnInit上,则小吃栏将无法正常工作,并且显示在页面错误的位置,您将无法再将其关闭。

IE IE

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 ngOnInit错误的结果: ngOnInit错误

Click on test button: click on test button 单击测试按钮: 单击测试按钮

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. 在很多情况下,错误处理程序将在Angular区域之外运行。 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 在这里,我找到了解决方案,并将其发布,以防其他人遇到相同的问题: https : //github.com/angular/material2/issues/9875

In my case, The solution was using this.handleError.bind(this) as shown below: 就我而言,解决方案使用this.handleError.bind(this) ,如下所示:

  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))
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM