【问题标题】:The new headers are not added with the interceptor新标头未与拦截器一起添加
【发布时间】:2019-12-07 10:00:07
【问题描述】:

我想为我的 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);
  }
}

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

【问题讨论】:

    标签: angular httpclient angular-http-interceptors


    【解决方案1】:

    来自官方文档:

    您不能直接修改前一个中的现有标题 options 对象,因为 HttpHeaders 类的实例是 不可变。

    请改用 set() 方法。它返回当前的克隆 应用了新更改的实例。

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

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

    【讨论】:

      【解决方案2】:

      给你,

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

      2) 根据您的要求,用新的或旧的覆盖标题

       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);
        }
      

      现在使用这些新标头克隆请求

      this.authReq = this.authReq.clone({
                      headers:
                          this.someService.setRequestHeaders(this.authReq)
                  });
      
      

      【讨论】:

        猜你喜欢
        • 2018-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 2018-03-04
        • 1970-01-01
        • 2018-06-21
        相关资源
        最近更新 更多