您可以使用Angular提供的Http Interceptor来实现这一点。拦截器是一个中间件,它拦截HTTP请求,可以用来修改请求和响应。
以下是一个示例,演示如何在请求头中添加Authorization标头:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
const authReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
});
return next.handle(authReq);
}
}
将此拦截器提供给您的应用程序:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]
})
export class AppModule { }