See Complete detail at ‘Interceptor in Angular’ and ‘Difference in Interceptors and guards in Angular?’
Interceptors - Add headers (e.g., authentication tokens).
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';@Injectable()
export class AuthInterceptor implements HttpInterceptor {intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
// Get the authentication token from your service or storage
const authToken = localStorage.getItem('authToken');if (authToken) {
// Clone the request and add the Authorization header
const authReq = request.clone({
headers: request.headers.set('Authorization', `Bearer ${authToken}`) });
// Pass the modified request to the next handler
return next.handle(authReq);
} else {
// If no token, just pass the original request
return next.handle(request);
}
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';import { AppComponent } from './app.component';
import { AuthInterceptor } from './auth.interceptor';@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Interceptors - Logging requests, responses
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable, tap } from 'rxjs';@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const startTime = Date.now();
let ok: string;// Extend the observable to log event times
return next.handle(request).pipe(
tap(
// Succeeds when there is a response; ignore other events
(event) => (ok = event instanceof HttpResponse ? 'succeeded' : ''),
// Errors also bubble up to the calling code
(error) => (ok = 'failed')
),
// Log when the call is complete
() => {
const endTime = Date.now();
const duration = endTime - startTime;
const message = `${request.method} ${request.urlWithParams} ${ok} in ${duration} ms.`;
console.log(message);
}
);
}
}