簡體   English   中英

如何在 Angular 5 HttpInterceptor 中添加多個標頭

[英]How to add multiple headers in Angular 5 HttpInterceptor

我正在嘗試學習如何使用HttpInterceptor向應用程序對 API 執行的每個 HTTP 請求添加幾個標頭。 我有這個攔截器:

import { Injectable } from '@angular/core';

import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';


@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const authReq = req.clone({
      headers: req.headers.set('Content-Type', 'application/json')
    });

    console.log('Intercepted HTTP call', authReq);

    return next.handle(authReq);
  }
}

除了'Content-Type'標頭之外,我還需要添加一個'Authorization'但我不知道該怎么做(Angular HttpHeaders 的文檔只是方法列表,沒有任何解釋)。

我該怎么做? 謝謝!

由於set方法每次都返回 headers 對象,因此您可以這樣做。 這樣,被攔截請求的原始標頭也將被保留。

const authReq = req.clone({
    headers: req.headers.set('Content-Type', 'application/json')
    .set('header2', 'header 2 value')
    .set('header3', 'header 3 value')
});

編輯:根據評論中的建議,我統一了兩個答案

覆蓋所有標題

@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  const authReq = req.clone({
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'my-auth-token'
    })
  });

  console.log('Intercepted HTTP call', authReq);

  return next.handle(authReq);
}

添加更多標題而不覆蓋(歸功於Ketan Patil - 請參閱本文中的答案)

const authReq = req.clone({
    headers: req.headers.set('Content-Type', 'application/json')
        .set('header2', 'header 2 value')
        .set('header3', 'header 3 value')
});

如前所述 - 接受的方法會覆蓋標頭,為了添加它們,我喜歡API 文檔中的方法

const authReq = req.clone({ setHeaders: { Authorization: authToken } });
  const modifiedReq = req.clone({
      url: this.setUrl(req.url),
      headers: this.addExtraHeaders(req.headers)
    });

和方法:

private addExtraHeaders(headers: HttpHeaders): HttpHeaders {
  headers = headers.append('myHeader', 'abcd');
  return headers;
} 

方法 .append 創建一個新的 HttpHeaders 對象,添加 myHeader 並返回新對象。

使用此解決方案意味着您還可以使用多個攔截器,因為您不會覆蓋標頭。

在你的攔截器文件中

import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  const auth = req.clone({
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Auth-Token': 'jwtToken'
    })
  });



  return next.handle(auth);
}



 **in app module**

import {HTTP_INTERCEPTORS} from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    {provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptorService, multi: true},
  ],
  bootstrap: [AppComponent]
})
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json');
    headers = headers.set('Authorization', 'my-auth-token');

    const authReq = req.clone({headers});
    console.log('Intercepted HTTP call', authReq);

    return next.handle(authReq);
  }
}

我嘗試了以下方法來使用攔截器發送自定義標頭。 請檢查鏈接stackBlitz

請參考控制台屏幕截圖以獲取您的參考瀏覽器控制台請求標頭

並添加了自定義標題

訪問控制請求標頭:authkey、內容類型、設備 ID

我希望將標頭添加為標頭的一部分,而不是在訪問控制請求標頭中。 請給我建議

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM