2
votes

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

1
Kindly share more code or a working stackblitz - Vikas
@Vikas sorry , I didn't notice that the link didn't show the code, now I updated it to show the code , I will add more code in the question too Thanks for the note - Ahmed Elkoussy

1 Answers

4
votes

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.