Angular 4.3.3 HttpClient : How get value from the header of a response?

angular httpclient headers
observe 'response' angular 7
angular 7 get response headers
angular 2 http get example
httpclient get headers c#
read response header in angular 6
httpoptions angular
angular httpclient get request headers

( Editor: VS Code; Typescript: 2.2.1 )

The purpose is to get the headers of the response of the request

Assume a POST request with HttpClient in a Service

import {
    Injectable
} from "@angular/core";

import {
    HttpClient,
    HttpHeaders,
} from "@angular/common/http";

@Injectable()
export class MyHttpClientService {
    const url = 'url';

    const body = {
        body: 'the body'
    };

    const headers = 'headers made with HttpHeaders';

    const options = {
        headers: headers,
        observe: "response", // to display the full response
        responseType: "json"
    };

    return this.http.post(sessionUrl, body, options)
        .subscribe(response => {
            console.log(response);
            return response;
        }, err => {
            throw err;
        });
}

HttpClient Angular Documentation

The first problem is that I have a Typescript error :

'Argument of type '{ 
    headers: HttpHeaders; 
    observe: string; 
    responseType: string;
}' is not assignable to parameter of type'{ 
    headers?: HttpHeaders;
    observe?: "body";
    params?: HttpParams; reportProgress?: boolean;
    respons...'.

Types of property 'observe' are incompatible.
Type 'string' is not assignable to type '"body"'.'
at: '51,49' source: 'ts'

Indeed, when I go to the ref of post() method, I point on this prototype (I Use VS code)

post(url: string, body: any | null, options: {
        headers?: HttpHeaders;
        observe?: 'body';
        params?: HttpParams;
        reportProgress?: boolean;
        responseType: 'arraybuffer';
        withCredentials?: boolean;
    }): Observable<ArrayBuffer>;

But I want this overloaded method :

post(url: string, body: any | null, options: {
    headers?: HttpHeaders;
    observe: 'response';
    params?: HttpParams;
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
}): Observable<HttpResponse<Object>>;

So, I tried to fix this error with this structure :

  const options = {
            headers: headers,
            "observe?": "response",
            "responseType?": "json",
        };

And It compiles! But I just get the body request as in json format.

Futhermore, why I have to put a ? symbol at the end of some name of fields ? As I saw on Typescript site, this symbol should just tell to the user that it is optional ?

I also tried to use all the fields, without and with ? marks

EDIT

I tried the solutions proposed by Angular 4 get headers from API response. For the map solution:

this.http.post(url).map(resp => console.log(resp));

Typescript compiler tells that map does not exists because it is not a part of Observable

I also tried this

import { Response } from "@angular/http";

this.http.post(url).post((resp: Response) => resp)

It compiles, but I get a unsupported Media Type response. These solutions should work for "Http" but it does not on "HttpClient".

EDIT 2

I get also a unsupported media type with the @Supamiu solution, so it would be an error on my headers. So the second solution from above (with Response type) should works too. But personnaly, I don't think it is a good way to mix "Http" with "HttpClient" so I will keep the solution of Supamiu

You can observe the full response instead of the content only. To do so, you have to pass observe: response into the options parameter of the function call.

http
  .get<MyJsonData>('/data.json', {observe: 'response'})
  .subscribe(resp => {
    // Here, resp is of type HttpResponse<MyJsonData>.
    // You can inspect its headers:
    console.log(resp.headers.get('X-Custom-Header'));
    // And access the body directly, which is typed as MyJsonData as requested.
    console.log(resp.body.someField);
  });

See HttpClient's documentation

javascript, You can observe the full response instead of the content only. To do so, you have to pass observe: response into the options parameter of the  ( Editor: VS Code; Typescript: 2.2.1 ) The purpose is to get the headers of the response of the request Assume a POST request with HttpClient in a Service import { Injectable } from "@angular/core"; import { HttpClient, HttpHeaders, } from "@angular/common/http"; @Injectable() export class MyHttpClientService { const url = 'url'; const body = { [&hellip;]

main problem of typecast so we can use "response" as 'body'

we can handle like

const options = {
    headers: headers,
    observe: "response" as 'body', // to display the full response & as 'body' for type cast
    responseType: "json"
};

return this.http.post(sessionUrl, body, options)
    .subscribe(response => {
        console.log(response);
        return response;
    }, err => {
        throw err;
    });

Angular 4.3.3 HttpClient : How get value from the header of , Editor: VS Code; Typescript: 2.2.1 ) The purpose is to get the headers of the response of the request Assume a POST request with HttpClient in  Angular 4.3 HttpClient (Accessing REST Web Services With Angular) import { HttpClient } from '@angular/common/http'; @Component We’re getting back a response which is confirming that the

Indeed, the main problem was a Typescript problem.

In the code of post(), options was declared directly in the parameters, so, as an "anonymous" interface.

The solution was to put directly the options in raw inside the parameters

http.post("url", body, {headers: headers, observe: "response"}).subscribe...

Communicating with backend services using HTTP, The ConfigService fetches this file with a get() method on HttpClient . Observable of configuration data, the component subscribes to the method's return value. showConfigResponse() method displays the response headers as well as the  This guide explains how to make HTTP GET requests using the HttpClient module in Angular. The Angular introduced the HttpClient Module in Angular 4.3. It is part of the package @angular/common/http. In this tutorial, let us build an HTTP GET example app, which sends the HTTP Get request to GitHub repository using the GitHub API.

If you use the solution from the top answer and you don't have access to .keys() or .get() on response.headers, make sure that you're using fetch rather than xhr.

Fetch requests are the default, but Angular will use xhr if xhr-only headers are present (e.x. x-www-form-urlencoded).

If you are trying to access any custom response headers, then you have to specify those headers with another header called Access-Control-Expose-Headers.

Angular HttpClient get Example, This page will walk through Angular HttpClient.get example. It sets headers for the http GET request. We need to assign values for observe property such as response for complete response, body for response with body  Step-by-Step Video Tutorial - Getting started with the new Angular HttpClient service to access REST web services. Real-world examples included. CodingTheSmartWay.com is a blog about latest technologies in web development, including Node.js, Meteor, React and Angular!

Angular 4.3 HttpClient (Accessing REST Web Services With Angular), This new module is available in package @angular/common/http and a Accessing the values by using data.login, data.bio and We're getting back a response which is confirming that the object has been created succesfully: Finally the newly created request object (with the header included) is passed  This page will walk through Angular HttpClient.get example. HttpClient has been introduced in Angular 4.3 version. HttpClient is smaller, easier and more powerful library for making HTTP requests. To use HttpClient we need to import HttpClientModule in our application module and then we can inject HttpClient in our components or services

Introduction to Angular's HttpClient ← Alligator.io, New with Angular 4.3, HttpClient replaces the standard Http library and You can pass-in an object with an observe key set to a value of 'response' to get the full response. This can be useful to inspect for certain headers: HttpClient methods return one valuelink. All HttpClient methods return an RxJS Observable of something. HTTP is a request/response protocol. You make a request, it returns a single response. In general, an observable can return multiple values over time. An observable from HttpClient always emits a single value and then completes, never to emit

The new Angular HttpClient API - Rxjx inDepth, One of the most notable changes is that now the response object is a JSON by HttpClient this.http.get('https://api.github.com/users') .subscribe(data the usage of object maps for parameters and headers of GET requests. Probably if you open developer tools and you inspect your response headers you should see the desired one. Who can choose which headers are exposed to javascript? Exposed headers are choosen by the web application (so your webservices, or your backend. Obviously you web application could be written using many languages and/or using many framework.

Comments
  • Possible duplicate of Angular 4 get headers from API response
  • @Hitmands I already saw this thread, however it use "Http" and not "HttpClient" , and Angular 4.3.3 seems to tend to use HttpClient now
  • Thank you! I get a unsupported data type but it would be a mistake on my headers
  • Does anyone have an idea how to do the same for http.patch() ? It doesn't work for me. The response is empty, when I want to have the raw response object with a status code.
  • Okay I just found out: it's http.patch(url, params, {observe: 'response'}) and make sure the response object is of type HttpResponse<object>
  • Thank you! I tried this but I'm not getting a value that appears in Response Headers in a network tab.
  • .get() is not a function in Angular 7
  • That typecasting part saved me lots of time and tension. Thanks Singh (Y)
  • life saver - this was driving me nuts. Still don't get why inlining the options hash works but post("url", body, options) doesn't. But yay!
  • @Gishu, the reason is explained in this answer. A solution without inlining that worked great for me is in this answer, although some changes may need to be made to the interface to make it match what you need.
  • this should work, but it doesn't work on my side, the "post method" is simply not being called, not sending or receiving anything in this setup, it works only if i put {observe: "response"} as the 3rd parameter