Igor Simic
4 years ago

Angular 6 Material Snack Bar - fire when interceptor throws a error




In this tutorial i will explain how to implement Material Design SnackBar and fire it whenever we got HTTP error status in our response.
To make this happen we have to first set up interceptor which will allow us to trigger SnackBar on error. In this post you can find the example how to do it.

So, let's start.

1. First let's create a snackbar component using Angular CLI. Open up command line tool go to your application app folder and trigger this line:
ng g component components/MatSnackBar
This will create mat-snack-bar.component files.

2. Let's include this component in our app. Go to app.module.ts and add these lines:
// in import section:
import { MatSnackBarComponent } from './components/mat-snack-bar/mat-snack-bar.component';

// in @ngModule
@NgModule({
  declarations: [
    ...
    MatSnackBarComponent,
   ],
  imports: [
    ...
    MatSnackBarModule
  ],
  providers: [AuthService,InterceptService,MatSnackBarComponent,
      {
       ...
      }
    ], 
  bootstrap: [AppComponent]
})

3. open up newly created mat-snack-bar.componenet and paste this code:
import {Component} from '@angular/core';
import {MatSnackBar} from '@angular/material';

@Component({
  selector: 'app-mat-snack-bar',
  templateUrl: './mat-snack-bar.component.html',
  styleUrls: ['./mat-snack-bar.component.css']
})
export class MatSnackBarComponent{

	constructor(public snackBar: MatSnackBar) {}

        // this function will open up snackbar on top right position with custom background color (defined in css)
	openSnackBar(message: string, action: string, className: string) {

 	    this.snackBar.open(message, action, {
	      duration: 2000,
	      verticalPosition: 'top',
	      horizontalPosition: 'end',
	      panelClass: [className],
	    });
	 }

}
mat-snack-bar.component.html and mat-snack-bar.component.css can stay 

4. Go to intercept.service.ts  and add snack bar component to it ( again to set up intercept service go to this link )
// in import section
import {MatSnackBarComponent} from "../components/mat-snack-bar/mat-snack-bar.component";

// ad it to constructor
	constructor(private authService: AuthService, private snackBar: MatSnackBarComponent ) { }

// call snackbar method when HTTP status code return error
// check response
	    return next.handle(request)
 	    .pipe(
	        tap(event => {
	          if (event instanceof HttpResponse) {
	             
	            console.log(" all looks good");
	            // http response status code
	            console.log(event);

	            // shows success snackbar with green background
	            //this.snackBar.openSnackBar(event.statusText,'Close','green-snackbar');
	          }
	        }, error => {
	   		// http response status code

	          	console.log("show error message");
	          	// show error snackbar with red background
	          	this.snackBar.openSnackBar(error.error.message,'Close','red-snackbar');

	        })
	      )



5. As you can see we are setting different class names in dependency whit kind of message should be displayed. Now we have to define these classes. Go to src/styles.css (or scss) and add these styles:
.blue-snackbar {
    background: #2196F3;
}
.green-snackbar {
    background: #1DE9B6;
}
.red-snackbar {
    background: #B00020;
}
And that is it!

More reading:
how to show multiple angular material SnackBar messages?

Thank you, and thank me!
:)