通过编写自定义拦截器来修改请求头。以下是一个示例:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export class HeadersInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest, next: HttpHandler) {
// 修改请求头
request = request.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem('token')}`
}
});
return next.handle(request);
}
}
在以上示例中,我们编写了一个名为 HeadersInterceptor 的自定义拦截器。该拦截器通过实现 HttpInterceptor 接口来将它作为 Angular 的 HTTP 拦截器。
在 intercept() 方法内部,我们可以访问到原始的 HTTP 请求。我们对请求头进行了修改,添加了一个 Authorization 头部,该头部包含了一个从本地存储获取的令牌。
最后,我们通过调用 next.handle() 方法来将新的 HTTP 请求传递给下一个拦截器,或者是传递给最终的 HTTP 处理程序。