javascript / expert
Snippet
Metadata-Driven Network Logic with HttpContext
Functional interceptors in Angular can utilize `HttpContext` to receive specific instructions from the calling service. By defining `HttpContextToken`s, you can pass metadata (like caching flags or retry policies) through the HTTP pipeline without polluting the URL or headers. This allows for highly flexible and reusable middleware.
snippet.js
1
2
3
4
5
6
7
8
9
10
import { HttpContext, HttpContextToken, HttpInterceptorFn } from '@angular/common/http';export const IS_CACHE_ENABLED = new HttpContextToken<boolean>(() => false);export const cacheInterceptor: HttpInterceptorFn = (req, next) => {if (req.context.get(IS_CACHE_ENABLED)) {console.log('Caching logic triggered for:', req.url);}return next(req);};
angular
Breakdown
1
export const IS_CACHE_ENABLED = new HttpContextToken<boolean>(() => false);
Creates a unique token for passing boolean metadata through HTTP requests.
2
if (req.context.get(IS_CACHE_ENABLED))
Retrieves the value of the token from the request context to decide on interceptor logic.