How Does The Interceptor Works in Angular
Angular HTTP interceptors function by intercepting the Angular HttpClient's HTTP requests and responses. They function as middleware, which enables you to apply common logic or changes to these requests and responses throughout your program.
Workflow of an Interceptor
1. Interception Point:
When an HTTP request is sent from your Angular application using the HttpClient, it is routed via the registered interceptors before reaching the server.
2. Intercept Method:
Each interceptor supports the HttpInterceptor interface, which require the implementation of the intercept method. This method accepts two parameters.
req: the outgoing HTTP request being intercepted.
next: An instance of HttpHandler which provides a handle method for passing the request to the next interceptor or the actual HttpClient.
3. Request Modification:
Inside the intercept method, you can : -
modify the req object, by clone the request and add headers, query parameters, or modify the request body.
Log details of the request for debugging purposes.
Transform the request before it is sent to the server.
4. Chain of Responsibility:
After processing the request in the interceptor, you call next.handle(req) to send the changed request to the next interceptor in the chain, or to the HttpClient if there are no more interceptors.
5. Response Handling:
When the request is made to the server, and a response is received: -
- The response is sent back through the interceptor chain in reverse order.
- Each interceptor can intercept and alter the response:
- Log response details.
- Transform the response data before passing it to the application code.
- Handle errors and HTTP status codes centrally.
6. Completion:
The application code that made the initial HTTP request eventually receives the final response (or error).
See Also: Angular Interceptors