I am trying to set header for post api as application.json
let options: { headers?: {'Content-Type':'application/json'} }
but not set.
To define the content-type with the new HttpClient class you need to:
@angular/common/http
(and NOT from @angular/http
which is currently marked as deprecated)import { HttpClient, HttpHeaders } from '@angular/common/http';
HttpClient
on the constructor:constructor(private http: HttpClient) { }
headers
to define the content-type desired and options
to prepare the object you will use on the call:private options = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
this.http.post('your target url', yourBodyObject, this.options)
where 'your target url'
and yourBodyObject
are used only as example and need to be replaced with your real data.
There is a section on this in the Angular Documentation - probably added quite recently:
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
TypeScript was giving me warnings when I tried to add a response type to httpOptions using the above format, so I use the following successfully:
let headers = new HttpHeaders({
'Content-Type': 'application/text'
});
return this.http.get(url, { responseType: 'text', headers })
Docs link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With