在Angular中,拦截器可以用来修改请求头和更改请求方法。以下是一个示例:
首先,创建一个拦截器类,实现HttpInterceptor
接口:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
intercept(request: HttpRequest, next: HttpHandler): Observable> {
// 修改请求头
const headers = request.headers.set('Authorization', 'Bearer your-token');
// 更改请求方法
const modifiedRequest = request.clone({
method: 'POST',
headers: headers
});
return next.handle(modifiedRequest);
}
}
然后,在你的模块或根模块中,将该拦截器提供给HTTP_INTERCEPTORS
:
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { CustomInterceptor } from './custom.interceptor';
@NgModule({
imports: [
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor,
multi: true
}
]
})
export class AppModule { }
通过以上步骤,你已经将拦截器应用到了整个应用程序。每次发出的HTTP请求都会经过该拦截器,其中请求头会被修改,请求方法会被更改。
请注意,以上示例中的your-token
应该替换为你的实际身份验证令牌。