ionic generate interceptor code example

Example: create interceptor file in ionic

import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { Injectable } from '@angular/core'; @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor() {} intercept(request: HttpRequest, next: HttpHandler): Observable<HttpEvent> { if (!request.headers.has('Content-Type')) { request = request.clone({ setHeaders: { 'Content-Type': 'application/json' } }); } return next.handle(request).pipe( map((event: HttpEvent) => { if (event instanceof HttpResponse) { // console.log('event--->>>', event); } return event; }), catchError((error: HttpErrorResponse) => { if (error.status === 401 || error.status === 500 || error.status === 0) { // handle the error // dismiss loading or show toast message } } )); } }

Tags:

Misc Example