[英]Unable to see the added headers to HTTP request in Angular
Following roughly this answer and checking with Angular docs on header manipulation , I added the following interceptor class (as shown here ).大致遵循这个答案并检查 Angular 文档关于header 操作,我添加了以下拦截器 class (如此处所示)。
NB.注意。 It gets invoked and other operation on the request object (like making it HTTPS etc.) work.它被调用并且对请求 object 的其他操作(比如使它成为 HTTPS 等)工作。 However, the neither the added/appended nor the updated/set header seem to show.但是,添加/附加或更新/设置 header 似乎都没有显示。
export class CoolInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler)
: Observable<HttpEvent<any>> {
request.headers.append("Shazoo", "Hazaa");
request.headers.set("Content-Type", "application/text");
console.log(request.headers);
return next.handle(request);
}
}
For some reason, the object displayed doesn't contain the manipulated headers.出于某种原因,显示的 object 不包含操纵的标题。 I'm getting the following.我得到以下内容。
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} HttpHeaders {normalizedNames:映射(0),lazyUpdate:null,标题:映射(0)}
If I manually run append
or set
in the console, I see that the object changes a bit.如果我手动运行append
或在控制台中set
,我看到 object 发生了一些变化。 Regrettably, it doesn't tell me anything useful that the lazyArray
contains an element now nor why it doesn't contain anything while printed during the execution.遗憾的是,它没有告诉我什么有用的lazyArray
现在包含一个元素,也没有告诉我为什么它在执行期间打印时不包含任何内容。
HttpHeaders {normalizedNames: Map(0), lazyUpdate: Array(1), headers: Map(0), lazyInit: HttpHeaders} HttpHeaders {normalizedNames: Map(0), lazyUpdate: Array(1), headers: Map(0), lazyInit: HttpHeaders}
I've been reeding on this for a while and I believe I got it right, except something small misstake that I'm unable to detect or diagnose.我已经研究了一段时间,我相信我做对了,除了一些我无法检测或诊断的小错误。
How do I alter the headers object of my request in the interceptor?如何在拦截器中更改我的请求的标头 object?
Or is the interceptor a poor choice of locations for such functionality, despite the docs ?或者,尽管有文档,但拦截器对于此类功能的位置选择是否不佳? That wouldfollow this suggestion .那将遵循这个建议。 I've also seen someone suggest a different approach by RequestOptions
and/or by altering the this.http.get(...)
parameters of the injected HttpClient
, like this .我还看到有人通过RequestOptions
和/或通过更改注入的HttpClient
的this.http.get(...)
参数提出了不同的方法,就像这样。
The set
method on HttpHeaders
doesn't mutate the object, but creates a copy. HttpHeaders
上的set
方法不会改变 object,但会创建一个副本。 Therefore, while因此,虽然
request.headers.set("Content-Type", "application/text");
won't work, [edit: request
itself is immutable, therefore it needs to be cloned]不起作用, [编辑: request
本身是不可变的,因此需要克隆]
const clonedWithRequiredHeaders = request.clone({
setHeaders: {"Content-Type": "application/text"},
})
should.应该。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.