如何在角度 5 中将标头设置为 HttpHeaders [英] How to set header to HttpHeaders in angular 5

查看:27
本文介绍了如何在角度 5 中将标头设置为 HttpHeaders的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何处理 HttpHeaders 上的标头,以便通过 HttpClient 将它们用于 http 请求.

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

它只能这样工作:

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

有没有特殊的方式来添加标题?还是bug?

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

推荐答案

这对我有用:

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 });
  }
}

这从一个私有变量开始,该变量使用 set 保存初始标头集.然后使用 append 在进行 Http 调用之前添加额外的标头.

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.

请注意,append 返回一个 HttpHeaders 对象,这就是我将输出分配给 const 的原因.仅仅运行 append 本身,认为现有的 _headers 会被改变,不会给你预期的结果.我确实确认 HttpHeaders 是不可变的.

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.

来自 HttpHeaders 文档:不可变的 Http 标头集,使用延迟解析.

这篇关于如何在角度 5 中将标头设置为 HttpHeaders的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆