I've been working on an app and needed to get access to some custom header values sent back from a service. In a normal situation, I'd do something like this:

view plain print about
1makeServiceCall(): Observable<object | MyCustomClass> {
2 return this.http.get(`url`).pipe(
3 map((response) =>
{
4 // processing if needed
5 Object.assign(new MyCustomClass(), response)
6 return myCustomResponse;
7 })
8 );
9 }

It works great, and gives our code custom typed objects to view and everything is good. However, I have no ability to access the custom header.

With some tweaks we can make it work. First, we need to pass an option argument to the HTTP request:

view plain print about
1makeServiceCall(): Observable<object | MyCustomClass> {
2 return this.http.get(`url`, { observe: 'response' })

The argument includes the observe property and it is set to response. That means instead of returning only the body from the call, you'll get the full HttpResponse object. Headers exist are accessible from the HttpResponse object.

view plain print about
1map((response: HttpResponse<object>) => {
2 // access header
3 console.log(response.headers.get('my-custom-header-name'));
4
5 // processing if needed
6 Object.assign(new MyCustomClass(), response.body)
7 return myCustomResponse;
8 })

We use the response.headers object to access the header information. To process our return data, we access response.body.

In my case, I was taking the custom header value and saving the data as part of my transformed response object for easy access later.