如何在 Angular 5 HttpInterceptor 中添加多个标头 [英] How to add multiple headers in Angular 5 HttpInterceptor
问题描述
我正在尝试学习如何使用 HttpInterceptor
向应用程序对 API 执行的每个 HTTP 请求添加几个标头.我有这个拦截器:
I'm trying to learn how to use HttpInterceptor
to add a couple of headers to each HTTP request the app do to the API. I've got this interceptor:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
});
console.log('Intercepted HTTP call', authReq);
return next.handle(authReq);
}
}
除了 'Content-Type'
标头我需要添加一个 'Authorization'
但我不知道怎么做(Angular HttpHeaders 的文档是只是方法列表,不做任何解释).
Apart of the 'Content-Type'
header I need to add an 'Authorization'
but I don't how to do it (the documentation of Angular HttpHeaders is just the list of the methods, without any explanation).
我该怎么做?谢谢!
推荐答案
根据评论中的建议,我统一了两个答案
Following suggestions in comments I have unified both answers
覆盖所有标题
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
});
console.log('Intercepted HTTP call', authReq);
return next.handle(authReq);
}
在不覆盖的情况下添加更多标题(归功于 Ketan Patil - 请参阅这个帖子)
Adding more headers without overwriting (credits to Ketan Patil - see answer in this post)
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
.set('header2', 'header 2 value')
.set('header3', 'header 3 value')
});
这篇关于如何在 Angular 5 HttpInterceptor 中添加多个标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!