Angular interceptors are very powerful tools that developers can use to manage how their applications handle HTTP requests and responses. They play a crucial role in implementing features like logging, authentication, error handling, and more, which leads to clearer and easier-to-maintain code.
Angular Interceptors act like a middleware between your Angular application and the server. They intercept requests before they are sent to the server and responses before they reach our application components. This allows developers to modify requests by adding headers, modifing request/response bodies, and changing status codes.
First, make sure you have Angular CLI installed. If not, you can install it with npm:
npm install -g @angular/cli
Now, create a new Angular project:
ng new Project_Name cd Project_Name
Now, Generate a new HTTP Interceptor with Angular CLI:
ng generate interceptor interceptors/interceptorName
This will create two files: interceptorName.interceptor.ts and interceptorName.interceptor.spec.ts in the src/app/interceptors directory.
Now , Open interceptorName.interceptor.ts and add the logic for your interceptor. Here’s an example that logs a message.
import { HttpInterceptorFn } from '@angular/common/http'; export const interceptorName: HttpInterceptorFn = (req, next) => { console.log('HTTP Request:', req); return next(req); };
Now, To use the interceptor, open app.config.ts and add it to the providers array:
... import { provideHttpClient,withInterceptors } from '@angular/common/http'; import { interceptorName } from './interceptors/interceptorName.interceptor'; export const appConfig: ApplicationConfig = { providers: [ .... provideHttpClient( withInterceptors([interceptorName]) ), ], };
Interceptors can tailor data transformation for requests and responses, such as modifying request bodies, headers, or response data formats before they are processed by the application.
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http'; export const apiInterceptor: HttpInterceptorFn = (req, next) => { const modifiedReq = req.clone({ body: { title:"Modified Request Body",id: 1 }, }); return next(modifiedReq); };
Developers can simulate different server situations without depending on live backend services by using interceptors to mock HTTP responses during testing. This method makes it possible to properly evaluate various scenarios.
import { HttpInterceptorFn } from '@angular/common/http'; import { of } from 'rxjs'; export const eventLoggingInterceptor: HttpInterceptorFn = (req, next) => { // Mock response for testing if (req.url.endsWith('/test')) { const mockResponse = { id: 1, title: 'Test Data' }; return of(new HttpResponse({ status: 200, body: mockResponse })); } // Pass through to actual HTTP request return next(req); }
Angular Interceptors enhance applications by implementing error-handling strategies, like automatically retrying failed requests and transforming error responses to improve user experience.
import { HttpInterceptorFn } from '@angular/common/http'; import { catchError,retry, throwError } from 'rxjs'; export const apiInterceptor: HttpInterceptorFn = (req, next) => { return next(req).pipe( retry(3), // Retry failed requests up to 3 times catchError((error) => { console.error('HTTP Error:', error); return throwError(error); }) ); };
Here, the interceptor retries the failed request up to three times before handling the error, ensuring multiple attempts to successfully complete the request.
In Angular, developers can link multiple interceptors, each managing different aspects of request processing like authentication, logging, or error handling. They run in the order they are registered, allowing precise modification of requests and responses, ensuring flexible management of workflows for enhanced application functionality.
import { HttpInterceptorFn, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; // First Interceptor: Authentication export const authInterceptor: HttpInterceptorFn = (req, next) => { const authReq = req.clone({ setHeaders: { Authorization: `Bearer YOUR_TOKEN` } }); return next(authReq); }; // Second Interceptor: Logging export const loggingInterceptor: HttpInterceptorFn = (req, next) => { console.log('Request URL:', req.url); return next(req).pipe( tap(event => { if (event instanceof HttpResponse) { console.log('Response Status:', event.status); } }) ); }; // Third Interceptor: Error Handling export const errorHandlingInterceptor: HttpInterceptorFn = (req, next) => { return next(req).pipe( retry(3), catchError((error) => { console.error('HTTP Error:', error); return throwError(error); }) ); }; // Registering Interceptors in Angular Module export const appConfig: ApplicationConfig = { providers: [ ... provideHttpClient( withInterceptors([apiInterceptor,loggingInterceptor,errorHandlingInterceptor]) ), ], };
Angular interceptors have the capability to intercept DOM events and interactions before Angular processes them. This functionality enables tasks like logging user interactions, enforcing application-wide event handling policies, or conducting additional validations prior to event propagation within the application.
import { HttpInterceptorFn } from '@angular/common/http'; export const eventLoggingInterceptor: HttpInterceptorFn = (req, next) => { document.addEventListener('click', (event) => { console.log('Click event intercepted:', event); // Additional custom event handling logic }); return next(req); };
External HTTP interception tools can be incredibly useful in various scenarios, especially when you need more control over your HTTP requests and responses beyond what is available in built-in interceptors. They are particularly beneficial for testing and debugging APIs, simulating different server conditions, and ensuring your application handles various edge cases effectively.
Requestly is one such powerful tool that enhances your development workflow. For example, suppose you’re developing an application and need to test how it handles a slow network response.
Les intercepteurs angulaires sont des outils indispensables pour gérer la communication HTTP et améliorer la robustesse des applications angulaires. En maîtrisant les méthodes et en explorant des solutions externes comme Requestly, les développeurs peuvent rationaliser les intégrations d'API, améliorer les pratiques de sécurité et optimiser efficacement les performances. Adoptez les intercepteurs pour améliorer la fiabilité et l'évolutivité de vos applications Angular en gérant diverses interactions backend avec confiance et efficacité.
The above is the detailed content of Understanding Angular Interceptors : Beyond HTTP. For more information, please follow other related articles on the PHP Chinese website!