Adding a HTTP header to the Angular HttpClient doesn't send the header, why?
The instances of the new HttpHeader
class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
or
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
Update: adding multiple headers
let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');
or
const headers = new HttpHeaders({'h1':'v1','h2':'v2'});
Update: accept object map for HttpClient headers & params
Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders
object an directly pass an object map as argument. So now its possible to do the following:
http.get('someurl',{
headers: {'header1':'value1','header2':'value2'}
});
To add multiples params or headers you can do the following:
constructor(private _http: HttpClient) {}
//....
const url = `${environment.APP_API}/api/request`;
let headers = new HttpHeaders().set('header1', hvalue1); // create header object
headers = headers.append('header2', hvalue2); // add a new header, creating a new object
headers = headers.append('header3', hvalue3); // add another header
let params = new HttpParams().set('param1', value1); // create params object
params = params.append('param2', value2); // add a new param, creating a new object
params = params.append('param3', value3); // add another param
return this._http.get<any[]>(url, { headers: headers, params: params })
set http headers like below in your http request
return this.http.get(url, { headers: new HttpHeaders({'Authorization': 'Bearer ' + token})
});