当在PUT调用中修改请求体中的属性时,Angular的拦截器会抛出错误。这是因为请求体被视为不可变的对象,所以任何修改操作都会被拦截器检测到并抛出错误。
要解决这个问题,可以采用以下方法之一:
clone()
方法创建请求的副本,并在副本上进行修改操作。这样原始请求体将保持不变,不会被拦截器检测到。import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
// 克隆请求
const clonedRequest = request.clone();
// 修改请求体中的属性
clonedRequest.body = { ...clonedRequest.body, newProperty: 'value' };
// 继续处理修改后的请求
return next.handle(clonedRequest);
}
}
headers
中。这样拦截器不会检测到请求体的变化。import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
// 添加要修改的属性到请求的headers中
const modifiedHeaders = request.headers.set('newProperty', 'value');
// 克隆请求并设置修改后的headers
const clonedRequest = request.clone({ headers: modifiedHeaders });
// 继续处理修改后的请求
return next.handle(clonedRequest);
}
}
这样,无论是通过修改请求体还是添加到headers中,都可以成功发送PUT请求,而不会被拦截器抛出错误。