Angular 8 - HttpInterceptor - 读取响应 headers
Angular 8 - HttpInterceptor - read response headers
我的 HttpInterceptor 的响应中缺少 http headers。我可以得到 body 但不能得到 headers。请参阅附件输出和我的代码。
@Injectable()
export class ApiVersionInterceptor implements HttpInterceptor {
intercept(
req: import("@angular/common/http").HttpRequest<any>,
next: import("@angular/common/http").HttpHandler
): import("rxjs").Observable<import("@angular/common/http").HttpEvent<any>> {
return next.handle(req).pipe(
tap(httpEvent=>{
// Skip request
if(httpEvent.type === 0){
return;
}
console.log("response: ", httpEvent);
})
);
}
}
使用如下所示的httpEvent.headers.get()
方法:
@Injectable()
export class ApiVersionInterceptor implements HttpInterceptor {
intercept(
req: import("@angular/common/http").HttpRequest<any>,
next: import("@angular/common/http").HttpHandler
): import("rxjs").Observable<import("@angular/common/http").HttpEvent<any>> {
return next.handle(req).pipe(
tap((httpEvent: HttpEvent<any>) =>{
// Skip request
if(httpEvent.type === 0){
return;
}
console.log("response: ", httpEvent);
let minTargetApiVersion : string;
if (httpEvent instanceof HttpResponse) {
if(httpEvent.headers.has('mintargetapiversion')) {
minTargetApiVersion = httpEvent.headers.get('mintargetapiversion');
}
}
})
);
}
}
哇哦,我解决了我的问题。
这不是Angular问题,而是服务器问题。我需要添加另一个 header:
"access-control-expose-headers": "mintargetapiversion"
如果未在 "access-control-expose-header" 中指定,Angular 将忽略自定义 header
我的 HttpInterceptor 的响应中缺少 http headers。我可以得到 body 但不能得到 headers。请参阅附件输出和我的代码。
@Injectable()
export class ApiVersionInterceptor implements HttpInterceptor {
intercept(
req: import("@angular/common/http").HttpRequest<any>,
next: import("@angular/common/http").HttpHandler
): import("rxjs").Observable<import("@angular/common/http").HttpEvent<any>> {
return next.handle(req).pipe(
tap(httpEvent=>{
// Skip request
if(httpEvent.type === 0){
return;
}
console.log("response: ", httpEvent);
})
);
}
}
使用如下所示的httpEvent.headers.get()
方法:
@Injectable()
export class ApiVersionInterceptor implements HttpInterceptor {
intercept(
req: import("@angular/common/http").HttpRequest<any>,
next: import("@angular/common/http").HttpHandler
): import("rxjs").Observable<import("@angular/common/http").HttpEvent<any>> {
return next.handle(req).pipe(
tap((httpEvent: HttpEvent<any>) =>{
// Skip request
if(httpEvent.type === 0){
return;
}
console.log("response: ", httpEvent);
let minTargetApiVersion : string;
if (httpEvent instanceof HttpResponse) {
if(httpEvent.headers.has('mintargetapiversion')) {
minTargetApiVersion = httpEvent.headers.get('mintargetapiversion');
}
}
})
);
}
}
哇哦,我解决了我的问题。
这不是Angular问题,而是服务器问题。我需要添加另一个 header:
"access-control-expose-headers": "mintargetapiversion"
如果未在 "access-control-expose-header" 中指定,Angular 将忽略自定义 header