In this article, we'll explore how to use functional HTTP interceptors with Angular 17. Interceptors allow manipulation of HTTP requests and responses, facilitating features such as adding headers, logging, authentication, and much more.
A working HTTP interceptor in Angular is a middleware function used to intercept and potentially transform outgoing requests and incoming responses. With Angular 17 you can use HttpInterceptorFn to create working interceptors.
Here is a simple example to illustrate how to create a working HTTP interceptor:
import { HttpRequest, HttpHandlerFn, HttpInterceptorFn } from '@angular/common/http'; export const loggingInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => { console.log(`Outgoing request to URL: ${req.url}`); return next(req).pipe( tap(event => { if (event instanceof HttpResponse) { console.log(`Response received from URL: ${req.url} with status: ${event.status}`); } }) ); };
In this example, the interceptor logs the URL of each outgoing request and the corresponding response.
To use this interceptor, you must configure it during application initialization using provideHttpClient and withInterceptors:
import { bootstrapApplication } from '@angular/platform-browser'; import { provideHttpClient, withInterceptors } from '@angular/common/http'; import { AppComponent } from './app/app.component'; import { loggingInterceptor } from './app/http-interceptors/logging-interceptor'; bootstrapApplication(AppComponent, { providers: [ provideHttpClient(withInterceptors([loggingInterceptor])) ] }).catch(err => console.error(err));
Functional Interceptors in Angular 17 provide a flexible and powerful way to handle HTTP requests and responses. They are particularly useful for cross-functional tasks like authentication, logging, and error handling.
For more details, see the official Angular documentation on interceptors【13†source】【14†source】.
The above is the detailed content of Interceptors in Angular. For more information, please follow other related articles on the PHP Chinese website!