Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

( 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

like image 617
SolidCanary Avatar asked Aug 04 '17 11:08

SolidCanary


People also ask

How do you pass headers in angular HTTP?

There are two ways by which we can add the headers. One, we add the HTTP Headers while making a request. The second way is to use the HTTP interceptor to intercept all the Requests and add the Headers. In both cases, we use the httpHeaders configuration option provided by angular HttpClient to add the headers.

What does HttpClient post return?

The HttpClient. post() returns Observable instance of given response type. On this page we will see injecting HttpClient , creating request body and passing HTTP options. We will also look into error handling. For the demo we will use Angular In-Memory Web API to post data.

What is observe response in angular?

Observe ResponseHttpClient object allows accessing complete response, including headers. In the browser, response body is a JSON object, which can be copied to a typescript interface or class type. Response headers are key/value pairs.


1 Answers

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

like image 199
Supamiu Avatar answered Oct 10 '22 12:10

Supamiu