Angular material snackbar in service?

Viewed 2246

I want to handle http error messages and show them using Angular material snackbar module within the service. I don't want to do all this repetitive work in the components. How can I do it? I get the following error: ERROR TypeError: this.openSnackBar is not a function . Note that it works fine in the component.

private handleError(error: HttpErrorResponse) {
    let message:string = "Something bad happened; please try again later."
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
     if(error.status == 404){

        this.openSnackBar('No data found!','Dismiss')
     }

    }
    console.log(error)
    // Return an observable with a user-facing error message.
    return throwError(message);
  }

openSnackBar(message: string, action: string) {
    this._snackBar.open(message, action, {
      duration: 2000,
    });
  }
1 Answers

MatSnackBar is just a service so you need to make sure of few things

  1. import MatSnackBarModule

    import {MatSnackBarModule} from '@angular/material/snack-bar';

  2. inject the MatSnackBar service.

  3. if you gone to use it inside a service make sure you mark that service with injectable decorator.

example

@Injectable({providedIn:'root'})
export class ErrorService { 

  constructor(private _snackBar: MatSnackBar){ }
   logError(message:string){
      this._snackBar.open(message,'Dismiss')
   }
} 

stackblitz demo

Updated

it look like you pass the handleError as a function reference in that case the this will reference other object and you get an error like the one you have

a quick fix is to use arrow function like this

private handleError = (error: HttpErrorResponse) => {
   ....
}

openSnackBar(message: string, action: string) {
...
}
Related