1

I'm trying to figure out how to handle headers on HttpHeaders to use them for http requests via HttpClient.

const headers = new HttpHeaders();
headers.append('foo', 'bar');
headers.set('foo', 'bar');

console.log(headers.get('foo')) // null

it works only this way:

const headers = new HttpHeaders().set('foo', 'bar');
console.log(headers.get('foo')) // bar

Is there a special way to add headers? Or it is a bug?

sandum
  • 751
  • 5
  • 13
  • 25

1 Answers1

8

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.

R. Richards
  • 24,603
  • 10
  • 64
  • 64