How to set header to HttpHeaders in angular 5 [duplicate]

末鹿安然 提交于 2020-06-01 06:16:10

问题


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:


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.



来源:https://stackoverflow.com/questions/47904687/how-to-set-header-to-httpheaders-in-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!