Welcome back to CodeYourCraft! Today, we're diving into the world of Angular Interceptors. Interceptors are a powerful tool that allows you to intercept HTTP requests and responses in Angular applications. Let's get started!
Interceptors are service providers that can intercept HTTP requests and responses. They can be used to modify or transform outgoing requests, or to process incoming responses before they are handled by the component that made the request.
Interceptors are useful for various purposes, such as:
To create an interceptor, follow these steps:
HttpInterceptor from @angular/common/http.HttpInterceptor.intercept method, which will be called for every outgoing request.HttpRequest and HttpHandler into the constructor.Here's a simple example of an interceptor that logs every outgoing request:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler) {
console.log('Outgoing request:', request);
return next.handle(request).do(
(event: HttpEvent<any>) => {
console.log('Incoming response:', event);
},
(error: any) => {
console.error('Error:', error);
}
);
}
}To use the interceptor, you need to:
AppModule's providers array.HttpClientModule's providers array.Here's how you can do it:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { LoggingInterceptor } from './logging.interceptor';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true },
],
bootstrap: [AppComponent]
})
export class AppModule { }What does an Angular Interceptor do?
That's it for today! In the next lesson, we'll dive deeper into Angular Interceptors and see how we can use them to add authorization headers to our requests.
Happy coding! 💻🚀