在 Angular 7 中,HttpInterceptor 可用于拦截和修改 HTTP 请求和响应。如果你遇到了无法将标头添加到请求的问题,可以尝试以下解决方法:
HttpInterceptor
接口,并正确地引入了 HttpInterceptor
和 HttpRequest
类:import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
// 在这里添加你的代码来修改请求
return next.handle(req);
}
}
intercept
方法中,你可以使用 clone
方法来创建一个新的 HttpRequest
对象,并在其中添加标头:intercept(req: HttpRequest, next: HttpHandler): Observable> {
const modifiedReq = req.clone({
headers: req.headers.set('headerName', 'headerValue')
});
return next.handle(modifiedReq);
}
providers
数组中注册了你的 HttpInterceptor
:@NgModule({
...
providers: [
...
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
],
...
})
export class AppModule { }
HttpClient
,而不是 Http
:import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
HttpInterceptor
,请确保它们的顺序是正确的。你可以使用 HttpInterceptors
数组来控制它们的顺序:{ provide: HTTP_INTERCEPTORS, useClass: MyFirstInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: MySecondInterceptor, multi: true },
通过检查以上步骤,你应该能够成功地将标头添加到请求中。如果问题仍然存在,请确保你使用的 Angular 版本正确,并检查开发者工具中的网络请求,以查看标头是否正确添加。