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);
}
}
It is possible to open a snackbar in any service. The key is a proper way of using
handleError()
function incatchError()
- context ofthis
must be bound with the handler function.Add
MatSnackBarModule
intoapp.module.ts
imports arrayUse the snackbar in any service, e.g.
MyService
like this: