π Angular Interceptors: Localization Interceptor
#angular #interceptor
#angular #interceptor
A localization interceptor can be used to automatically include the userβs preferred language or locale in HTTP requests, ensuring that the server sends responses in the appropriate language.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
import { LocaleService } from './locale.service';
@Injectable()
export class LocalizationInterceptor implements HttpInterceptor {
constructor(private localeService: LocaleService) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
const userLocale = this.localeService.getUserLocale();
const localizedRequest = request.clone({
setHeaders: {
'Accept-Language': userLocale,
},
});
return next.handle(localizedRequest);
}
}π₯3
π Content Security Policy (CSP) Interceptor
#angular #interceptor
#angular #interceptor
A CSP interceptor can be used to automatically add Content Security Policy headers to outgoing HTTP requests to improve security.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
@Injectable()
export class CspInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<any>,
next: HttpHandler
) {
const cspHeader = "default-src 'self'; script-src 'self' 'unsafe-inline'";
const cspRequest = request.clone({
setHeaders: {
'Content-Security-Policy': cspHeader,
},
});
return next.handle(cspRequest);
}
}π Angular Interceptors: Compression Interceptor
#angular #interceptor
#angular #interceptor
A compression interceptor can be used to automatically request compressed content (e.g., gzip) from the server, reducing the amount of data transferred over the network.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
@Injectable()
export class CompressionInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
const compressedRequest = request.clone({
setHeaders: {
'Accept-Encoding': 'gzip, deflate'
},
});
return next.handle(compressedRequest);
}
}#angular #error #interceptor
β οΈ The example is for presentation purposes only and can be refactored.
β Article link
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
π1