Open puddlejumper26 opened 4 years ago
Here we write a sample, the browser will display a toast (angular material) when the server is down.
toast
@Injectable() <==== export class ServerErrorInterceptor implements HttpInterceptor { constructor(private readonly snackBar: MatSnackBar) { } public intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> { return new Observable((subscriber) => { next.handle(req).subscribe( (value) => subscriber.next(value), (error) => { this.handleError(error, req, next, subscriber); }, ); }); } private handleError<T>(error: HttpErrorResponse, req: HttpRequest<T>, next: HttpHandler, subscriber: Subscriber<HttpEvent<T>>) { const isServerError = Math.floor(error.status / 100) === 5; if (error.status === 0 || isServerError) { this.snackBar.open( 'Server Error is happening', 'Hide', { duration: 5000 }, ); } } }
app.module.ts
const SERVER_ERROR_INTERCEPTOR: Provider = { multi: true, provide: HTTP_INTERCEPTORS, useExisting: forwardRef(() => ServerErrorInterceptor), }; @NgModule({ SERVER_ERROR_INTERCEPTOR, <==== ServerErrorInterceptor, <==== }) export class AppModule { }
[1] https://angular.io/guide/http#http-interceptors
Write an Interceptor
Here we write a sample, the browser will display a
toast
(angular material) when the server is down.app.module.ts
Reference
[1] https://angular.io/guide/http#http-interceptors