How i can display a MatSnackBar from a Service with Angular Material?

Simón Farias picture Simón Farias · Nov 4, 2018 · Viewed 11.3k times · Source

Im using: Angular V6.1.0, Angular Material V6.4.1

Im trying catch the HTTP errors and show them using a MatSnackBar. I seek to show this in every component of my application (where there is an http request). So as not to do the repetitive code

Otherwise i should repeat the same code in every component for display the MatSnackBar with the errors inserted.

This is my service:

Answer

mchl18 picture mchl18 · Nov 5, 2018

Create a service with this:

custom-snackbar.service.ts

import { Injectable, NgZone } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';

@Injectable()
export class CustomSnackbarService {
    constructor(
      private snackBar: MatSnackBar,
      private zone: NgZone
    ) {
       
    }

    public open(message: string, action = 'success', duration = 4000): void {
        this.zone.run(() => {
          this.snackBar.open(message, action, { duration });
        });
    }
}

Add the MatSnackBarModule to the app.module.ts:

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

...
imports: [
    BrowserModule,
    AppRoutingModule,
    MatSnackBarModule,
],
...

Also it needs to be run in ngZone: https://github.com/angular/material2/issues/9875

Then in the error-service.ts:

public handleError (error: HttpErrorResponse | any) {
  customSnackbarService.open(error, 'error')
  return throwError(error);
}