This works for me:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
const url = `https://sampleapi.com`;
@Injectable()
export class BasicService {
private _headers = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private httpClient: HttpClient) { }
getWithHeader(): Observable<any> {
const headers = this._headers.append('foo', 'Bar');
return this.httpClient.get<any>(url, { headers : headers });
}
}
This starts with a private variable that holds the initial set of headers, using set
. Then uses append
to add an additional headers before making the Http call.
Note that append
returns an HttpHeaders object, which is why I assign the output to a const. Just running append
by itself, thinking that the existing _headers
will be changed, will not give you the results you might expect. I did confirm that HttpHeaders are immutable.
EDIT: From the HttpHeaders docs: Immutable set of Http headers, with lazy parsing.