问题描述
我试图弄清楚如何处理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
它只能通过这种方式工作:
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?
推荐答案
这对我有用:
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标头集,延迟解析.
这篇关于如何在Angular 5中将标头设置为HttpHeaders的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!