Fel*_*Fel 19 angular-http-interceptors angular angular-httpclient
我正在尝试学习如何使用HttpInterceptor为应用程序对API执行的每个HTTP请求添加几个标头.我有这个拦截器:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
}
除了'Content-Type'标题之外,我还需要添加'Authorization',但我不知道怎么做(Angular HttpHeaders的文档只是方法列表,没有任何解释).
我该怎么做?谢谢!
Ket*_*til 31
由于该set方法每次都返回头对象,因此您可以执行此操作.这样,来自截获的请求的原始标头也将被保留.
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
.set('header2', 'header 2 value')
.set('header3', 'header 3 value')
});
Run Code Online (Sandbox Code Playgroud)
axl*_*ode 28
@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);
}
Run Code Online (Sandbox Code Playgroud)
vit*_*sai 11
如前所述-可接受的方法会覆盖标头,为添加标头,我喜欢API文档中的方法:
const authReq = req.clone({ setHeaders: { Authorization: authToken } });
Run Code Online (Sandbox Code Playgroud)
const modifiedReq = req.clone({
url: this.setUrl(req.url),
headers: this.addExtraHeaders(req.headers)
});
Run Code Online (Sandbox Code Playgroud)
和方法:
private addExtraHeaders(headers: HttpHeaders): HttpHeaders {
headers = headers.append('myHeader', 'abcd');
return headers;
}
Run Code Online (Sandbox Code Playgroud)
方法 .append 创建一个新的 HttpHeaders 对象,添加 myHeader 并返回新对象。
使用此解决方案意味着您还可以使用多个拦截器,因为您不会覆盖标头。
| 归档时间: |
|
| 查看次数: |
26360 次 |
| 最近记录: |