Http 拦截器

大多数拦截器检查请求的方式,并将(可能已更改的)请求转发给实现接口handle()next对象的方法HttpHandler

  1. import {Injectable} from "@angular/core";
  2. import {HttpEvent, HttpHandler, HttpInterceptor} from "@angular/common/http";
  3. import {HttpRequest} from "@angular/common/http";
  4. import {Observable} from "rxjs/Observable";
  5. @Injectable()
  6. export class AuthInterceptor implements HttpInterceptor {
  7. constructor(private authService: AuthService) {
  8. }
  9. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  10. const clonedRequest = req.clone({
  11. headers: req.headers.set('X-CustomAuthHeader', authService.getToken())
  12. });
  13. console.log("new headers", clonedRequest.headers.keys());
  14. return next.handle(clonedRequest);
  15. }
  16. }

配置拦截器

  1. @NgModule({
  2. declarations: [
  3. AppComponent
  4. ],
  5. imports: [
  6. BrowserModule,
  7. HttpClientModule
  8. ],
  9. providers: [
  10. [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ]
  11. ],
  12. bootstrap: [AppComponent]
  13. })
  14. export class AppModule { }

一个改变HTTP头的拦截器可以用于许多不同的操作,包括:

  • 认证/授权
  • 缓存行为; 例如,If-Modified-Since
  • XSRF保护