Skip to content

Instantly share code, notes, and snippets.

@taylorhutchison
Last active December 2, 2022 13:17
Show Gist options
  • Save taylorhutchison/6700eae2338956f04a7b9d7ddaa6fd53 to your computer and use it in GitHub Desktop.
Save taylorhutchison/6700eae2338956f04a7b9d7ddaa6fd53 to your computer and use it in GitHub Desktop.
An Angular interceptor to show a Material Snackbar on success or error of an HTTP POST/PUT.
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap, } from 'rxjs/operators';
import { MatSnackBar } from '@angular/material/snack-bar';
@Injectable()
export class SnackbarInterceptor implements HttpInterceptor {
constructor(private snackBar: MatSnackBar) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
tap(e => {
if (request.method == "POST" || request.method == "PUT")
if (e instanceof HttpResponse && e.status == 200) {
this.snackBar.open('Saved successfully.', 'close', { duration: 2000, panelClass: 'successSnack' });
}
}),
catchError(error => {
this.snackBar.open('Error while saving.', 'close', { duration: 2000, panelClass: 'errorSnack' });
return throwError(error);
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment