在Angular 10中,HttpInterceptor
的工作方式有所变化,可能导致无法正确拦截请求。解决这个问题的方法是在拦截器中使用新的HttpRequest
对象来处理请求。以下是一个解决方案的示例代码:
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.headers.append('Authorization', 'Bearer your_auth_token');
// 使用新的克隆请求对象继续处理请求
return next.handle(clonedRequest);
}
}
请注意,HttpRequest
对象是不可变的,所以我们需要使用clone()
方法创建一个副本,并对副本进行修改。在示例代码中,我们通过headers.append()
方法添加了一个授权头部。
然后,我们将修改后的请求对象传递给next.handle()
方法来继续处理请求。
要在应用中使用拦截器,需要在AppModule
或特定模块中提供HTTP_INTERCEPTORS
常量,并将自定义拦截器添加到拦截器数组中。例如:
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { CustomInterceptor } from './custom.interceptor';
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor,
multi: true // 多个拦截器时需要设置为true
}
]
})
export class AppModule { }
这样,CustomInterceptor
就会被应用到所有的HTTP请求中。
请注意,如果你有多个拦截器,拦截器的处理顺序将按照提供的顺序进行。