(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1)
The main objective here is to fetch the headers of the response from a request
Let's consider a scenario where we make a POST request using HttpClient within 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;
});
}
Angular HttpClient Documentation
The issue begins with 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'
It seems that I want to use an overloaded method for post() but encountering compatibility issues.
While attempting to fix the error by adjusting the structure like this:
const options = {
headers: headers,
"observe?": "response",
"responseType?": "json",
};
Although it compiles, I am only receiving the request body in JSON format.
Additionally, there is confusion around why some field names are followed by a '?' symbol. According to the Typescript documentation, this denotes optional fields.
I have also experimented with all the fields, both with and without '?', but had no success.
EDIT
Trying out solutions recommended on Stack Overflow regarding getting headers from API response in Angular 4. For the map solution:
this.http.post(url).map(resp => console.log(resp));
The Typescript compiler indicates that map does not exist as part of Observable.
Another attempt:
import { Response } from "@angular/http";
this.http.post(url).post((resp: Response) => resp)
This code compiles, but results in an unsupported Media Type response. These solutions should work for "Http" but not with "HttpClient".
EDIT 2
Even after trying the @Supamiu solution, I continue to face unsupported media type issue, suggesting an error in my headers. Therefore, the second solution mentioned earlier (using Response type) should ideally work. However, personally, mixing "Http" with "HttpClient" might not be the best approach, so I will stick to the Supamiu's solution.