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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can we use headers.append in loop to add multiple values from json array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.