Read Custom HTTP Headers Sent by the Server in Angular

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

By default the response body doesn’t contain all the data that might be needed in your app. Your server might return some special header which you have to read explicitly. In such case we can use the { observe: ‘response’} configuration of the Angular HttpClient. Let’s explore how.

When we execute an HTTP request to our backend, you can see how we get back to data. In this case, we even specify Tom typing here, so we want to get back an instance of a person which we can then access here in our subscribe callback in our app component for instance.

What if we are interested in actually some custom headers which our response gives us back? For instance, in this example here, in the response headers here after we request, you can see there is the my custom header. I would like to read that header out.

In order to do so, I have to change basically the call here because the person itself only contains the raw data coming from the response body. I'm interested also in the header values in this case. To do so, we can specify here so-called observe value.

The observe value specifies what we are currently interested in in observing and therefore also changes here the response type of our HTTP request. We could have here different kind of values, for instance, events when you are interested in HTTP events. We would get here an observable of an HTTP event.

In our case, we are interested in the response specifically. According to here we get now an HTTP response of type person. We need to import that from the common HTTP package. We can now go to our app component here. Let's Console log what comes back from data.

If I execute request, you can see now we have a series of properties here which is our response object actually that gets printed here out on our UI. Now, to retrieve our custom header, what we can do here is to access the header property. Then we use the get method and specify here my custom header which is the header name I specified on the server side.

Again, executing here the request and then looking here in response headers, I can see that my custom header gets back again. Here also now on the Console, we get Angular rocks printed out which is actually the value of that my custom header.