Transform Http Requests in Angular using Interceptor
Hello everyone, in this tutorial we will implement Http Interceptor in Angular. Interceptors allow us to tap into Http requests/responses globally in order to perform our required transformations.
Here we will use the Http Interceptor to include our sample token in every request header and also to modify the response. This can be useful when all our endpoints are secured and we need to pass on the authentication information in every request header.
For the demo purpose, JsonPlaceholder, which is a fake online REST API, will work as our back end.
Add Sample Token to Session Storage
Add a button to the app.component.html file which we will use to simulate the login by adding a sample token to the session storage
On click event of this button, add sample string with key “token” in the browser. In real world apps this token will most probably hold your JWT or normal bearer token
On clicking the GetSecureData button we can see the data logged in the console. On moving to the network tab and in our particular Api call, we can see the header added as well.
Note: JsonPlaceholder API’s are unsecured and do not require any credentials to access data. We are just using them here to demonstrate how all API calls can be modified so as to include authentication headers or for any other transformation as well.
Transform Response using Interceptor
We will transform the response in the next.handle() method by using the pipe and map operators and checking the instance of the object
Import the map operator in the interceptor service from ‘rxjs/operators’