在Angular 8中,可以使用HttpInterceptor来拦截HTTP请求和响应。要读取响应头部,可以按照以下步骤进行操作:
ng generate service my-http-interceptor
HttpInterceptor
和HttpRequest
、HttpHandler
、HttpEvent
等相关类:import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
@Injectable()
export class MyHttpInterceptorService implements HttpInterceptor {
constructor() { }
}
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
// 读取响应头部信息
const headers = event.headers;
console.log(headers.get('header-name'));
}
})
);
}
在intercept方法中,通过调用next.handle(req)来继续处理HTTP请求。然后使用pipe和tap操作符来处理响应。当响应类型是HttpResponse时,可以通过event.headers来读取响应头部信息。
在应用的根模块(通常是app.module.ts)中,将MyHttpInterceptorService添加到providers数组中,以便将其注册为全局的HTTP拦截器:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyHttpInterceptorService } from './my-http-interceptor.service';
@NgModule({
imports: [...],
declarations: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyHttpInterceptorService,
multi: true
}
],
bootstrap: [...]
})
export class AppModule { }
通过以上步骤,就可以在Angular 8中使用HttpInterceptor来读取响应头部信息。注意,上述代码示例仅包含了读取响应头部的部分,你可以根据实际需求进行自定义处理。