HTTP Interceptor in Angular 4
December 17, 2017The former approach:
The request to a web API endpoint from a service can be represented by the image below.
Think of interceptor as an intermediate between the HTTP request from service and the web API endpoint. All the requests that initiate from an Angular service, passes through the interceptor, which then processes the HTTP request and modifies it to be sent to the server, in our case attaching the "Authorization" header to the request to be sent.
The below image shows how an Http Interceptor works for an Angular application
Not only the request, we can also handle the response from an HTTP Interceptor. If the status code of the response is not Ok (200), then we need to show some failure message to the user.
Note that, Http interceptor is a new concept and has been introduced in latest Angular 4 version and it only works with HttpClient Module, which is a replacement for Http module. So make sure you are using the Http Client module in your angular project to make HTTP requests.
The new approach:
Luckily, Angular comes with a solution to this problem. The solution is creating an "Http Interceptor".Think of interceptor as an intermediate between the HTTP request from service and the web API endpoint. All the requests that initiate from an Angular service, passes through the interceptor, which then processes the HTTP request and modifies it to be sent to the server, in our case attaching the "Authorization" header to the request to be sent.
The below image shows how an Http Interceptor works for an Angular application
Not only the request, we can also handle the response from an HTTP Interceptor. If the status code of the response is not Ok (200), then we need to show some failure message to the user.
Note that, Http interceptor is a new concept and has been introduced in latest Angular 4 version and it only works with HttpClient Module, which is a replacement for Http module. So make sure you are using the Http Client module in your angular project to make HTTP requests.
0 comments