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:
import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
// import { HttpClient, HttpErrorResponse, HttpRequest } from '@angular/common/http';
import { Observable, throwError, of, interval, Subject } from 'rxjs';
import { map, catchError, retryWhen, flatMap } from 'rxjs/operators';
import { url, ErrorNotification } from '../globals';
import { MatSnackBar } from '@angular/material';
import { ErrorNotificationComponent } from '../error-notification/error-notification.component';
@Injectable({
providedIn: 'root'
})
export class XhrErrorHandlerService {
public subj_notification: Subject<string> = new Subject();
constructor(
public snackBar: MatSnackBar
) {
}
public handleError (error: HttpErrorResponse | any) {
this.snackBar.open('Error message: '+error.error.error, 'action', {
duration: 4000,
});
return throwError(error);
}
}
Import the snackBarService and inject it inside the constructor of the component, in which you want to use the Snackbar. This will create an instance of the service say snackBService. Now call the openSnackBar function wherever it is required, with the help of snackBService.
MatSnackBar is a service for displaying snack-bar notifications. Basic snack-bar.
Use snackBarRef. dismiss() to close it. If you face any flickering on showing snack bar, run it inside the Ngzone.
Angular Material Version 5.2.2 This is the last version of material that we can see on the angular material official website, you can start using this one if you want to. It has come up with a very basic component.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With