See Complete detail at ‘Interceptor in Angular’ and ‘Difference in Interceptors and guards in Angular?

 

 

Interceptors - Global error handling).

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   return next.handle(request).pipe(
     catchError((error: HttpErrorResponse) => {
       let errorMessage = '';
       if (error.error instanceof ErrorEvent) {
         // Client-side error
         errorMessage = `Error: ${error.error.message}`;
       } else {
         // Server-side error
         errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
       }
       console.error(errorMessage);
       // Optionally, you can display a user-friendly message or perform other error handling logic here
       // this.notificationService.showError(errorMessage);
       return throwError(() => error); // Re-throw the error to be caught by the component
     })
   );
 }
}

 

Interceptors - Cache replies.

interface CacheEntry {
 url: string;
 response: HttpResponse<any>;
 lastRead: number;
}

const maxCacheAge = 300000; // 5 minutes

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
 private cache = new Map<string, CacheEntry>();

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   // Only cache GET requests
   if (request.method !== 'GET') {
     return next.handle(request);
   }

   const cachedResponse = this.cache.get(request.urlWithParams);

   if (cachedResponse && (Date.now() - cachedResponse.lastRead) < maxCacheAge) {
     // Return the cached response
     cachedResponse.lastRead = Date.now();
     return of(cachedResponse.response.clone());
   }

   // Send the request and cache the response
   return next.handle(request).pipe(
     tap(event => {
       if (event instanceof HttpResponse) {
         this.cache.set(request.urlWithParams, { url: request.urlWithParams, response: event, lastRead: Date.now() });
         // Optionally, remove outdated cache entries
         this.deleteOutdatedCache();
       }
     })
   );
 }

 private deleteOutdatedCache() {
   const now = Date.now();
   this.cache.forEach(entry => {
     if ((now - entry.lastRead) > maxCacheAge) {
       this.cache.delete(entry.url);
     }
   });
 }
}

 

Interceptors -  Transforming requests/responses.

@Injectable()
export class TransformInterceptor implements HttpInterceptor {
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   // Example: Add a custom header to all requests
   const transformedRequest = request.clone({
     headers: request.headers.set('X-Custom-Header', 'AngularInterceptor')
   });

   return next.handle(transformedRequest).pipe(
     map((event: HttpEvent<any>) => {
       if (event instanceof HttpResponse) {
         // Example: Unwrap a nested 'data' property in the response body
         if (event.body && event.body.data) {
           const transformedBody = event.body.data;
           return event.clone({ body: transformedBody });
         }
       }
       return event;
     })
   );
 }

 


Related Question