Reputation: 8568
I am trying to show a material snackbar for the backend errors in my Angular 5 application.
I tried multiple ways but none worked, seems that the ErrorHandler class needs some special way to call the snackbar correctly.
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) :
@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
Upvotes: 2
Views: 1875
Reputation: 5686
Angular loads ErrorHandler before the providers, this is the reason for your error about cyclic dependency.
So you need to inject the MatSnackBar manually, using the Injector, as this way:
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.
Upvotes: 4