[英]Can't show a material snackbar for the backend errors using custom ErrorHandler Angular 5
I am trying to show a material snackbar for the backend errors in my Angular 5 application. 我正在尝试为Angular 5应用程序中的后端错误显示一个实质性的小吃栏。
I tried multiple ways but none worked, seems that the ErrorHandler class needs some special way to call the snackbar correctly. 我尝试了多种方法,但没有任何效果,似乎ErrorHandler类需要一些特殊的方法来正确调用点心栏。
Can someone please advise how to handle this? 有人可以建议如何处理吗?
I am getting this error: 我收到此错误:
Provider parse errors:
Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
Evaluating main.ts
My custom ErrorHandler class is (without the imports) : 我的自定义ErrorHandler类是(没有导入):
@Injectable()
export class MyErrorHandler implements ErrorHandler {
constructor(public snackBar: MatSnackBar) {}
handleError(error) {
const errorMsg = 'an error has happened';
this.openSnackBar(errorMsg);
}
openSnackBar(message: string) {
this.snackBar.open(message);
}
}
This is a stackblitz example to show what I mean 这是一个说明问题的例子
Note: 注意:
I have found this error in multiple questions but I can't exactly map the answers to my case 我在多个问题中发现了此错误,但我无法将答案完全映射到我的案例中
Angular loads ErrorHandler before the providers, this is the reason for your error about cyclic dependency. Angular在提供程序之前加载ErrorHandler,这是导致您关于循环依赖性错误的原因。
So you need to inject the MatSnackBar manually, using the Injector, as this way: 因此,您需要使用Injector手动注入MatSnackBar,如下所示:
import { Injectable, Injector } from '@angular/core';
import { MatSnackBar } from '@angular/material';
@Injectable()
export class MyErrorHandler implements ErrorHandler {
private snackbar;
constructor(private injector: Injector) {}
handleError(error) {
this.snackBar = this.injector.get(MatSnackBar);
const errorMsg = 'an error has happened';
this.openSnackBar(errorMsg);
}
openSnackBar(message: string) {
this.snackBar.open(message);
}
}
I have modified your stackblitz , now it works. 我已经修改了您的stackblitz ,现在可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.