In Angular, an interceptor is a service you can create to intercept and manipulate HTTP requests or responses before they are sent or received by your application. Interceptors allow the execution of common logic centrally on all HTTP requests or responses, as adding headers, handling errors, authenticating requests, among other operations.
Interceptors implement Angular's "HttpInterceptor" interface, which defines a method called "intercept". This method is called for each HTTP request before the request is sent to the server or for each response before it is delivered to the code that made it.
Basic Structure of an Interceptor
Following is the basic structure of an interceptor in Angular.
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// Interceptor logic here
// Modify the req, add headers, manipulate the response, etc.
// Pass the modified request to the next handler in the chain
return next.handle(req);
}
}
Registering an Interceptor
You need to register your interceptors in your application module. This is done by providing them as providers in the "HTTP_INTERCEPTORS" array.
// app.module.ts
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './path/to/your/interceptor';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './path/to/your/interceptor';
@NgModule({
imports: [HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi:true
}
// ... other providers
],
})
export class AppModule { }
Common Uses of Interceptors
Add Headers
You can automatically add headers to all requests, such as authentication tokens.
Handle Responses
You can intercept responses to handle errors globally or perform common actions before the response reaches the code that made it.
Authentication
You can use interceptors to automatically add authentication information to each request.
Handle Errors
Interceptors can be used to handle errors centrally, such as displaying an error message to the user or redirecting to a login page.
Cache and Local Storage
Interceptors can be used to implement caching or local storage strategies to optimize repeated requests.
Interceptors provide a powerful way to extend and customize the default "HttpClient" behavior in Angular, helping to keep code more modular, reusable, and maintainable.
Nenhum comentário:
Postar um comentário