新的 headers 没有添加拦截器

The new headers are not added with the interceptor

我想将 header 添加到我的 Angular 8 应用程序中的所有 HTTPClients。这是我的拦截器:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class Interceptor implements HttpInterceptor {
  constructor(private toaster: ToastrService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    alert('Interceptor!');

    // Set headers
    const headers = req.headers;

    // Set this header for security
    headers.set('test', 'value');

    const authReq = req.clone({ headers });

    return next.handle(authReq);
  }
}

警报已执行,但测试 header 未添加到请求中。

来自官方文档:

You can't directly modify the existing headers within the previous options object because instances of the HttpHeaders class are immutable.

Use the set() method instead. It returns a clone of the current instance with the new changes applied.

您需要克隆请求并在那里设置 headers。

const newReq =  req.clone({ headers: req.headers.set('test', 'value') });
return next.handle(newReq);

给你,

1) 您可以使用现有的和添加新的,并可以放置在一些实用程序中以重复用于所有拦截请求

2) 根据您的要求用新的或旧的覆盖 headers

 setRequestHeaders(req: HttpRequest<any>): HttpHeaders {
    const headerSettings: { [name: string]: string | string[]; } = {};
    // GET ALL EXISTING HEADERS
    for (const key of req.headers.keys()) {
      headerSettings[key] = req.headers.getAll(key);
    }

    // ADD NEW HEADERS
    headerSettings[COMMON_CONSTANTS.HEADERS.AUTHORIZATION] = 
        : 'Bearer some-random-token';
    headerSettings[COMMON_CONSTANTS.HEADERS.CACHE_CONTROL] = 'max-age=0, no-cache, must-revalidate, proxy-revalidate';   

    return new HttpHeaders(headerSettings);
  }

现在使用这些新的 headers

克隆请求
this.authReq = this.authReq.clone({
                headers:
                    this.someService.setRequestHeaders(this.authReq)
            });