Interceptor Angular 4.3 - 在克隆请求上设置多个标头

时间:2017-08-07 17:37:28

标签: angular header interceptor

我刚刚注意到新的拦截器不再支持以前的HTTP RequestsOption中可能使用的Header Object

new Interceptor逻辑:

// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});

我现在有两种方法可以在此请求中添加标题:

示例:

headers?: HttpHeaders;

    headers: req.headers.set('token1', 'asd')
setHeaders?: {
   [name: string]: string | string[];
};

    setHeaders: {
             'token1': 'asd',
             'token2': 'lol'
    }

如何在此请求中有条件地添加多个标头? 与我以前对标题对象的操作相同:

 myLovellyHeaders(headers: Headers) {
    headers.set('token1', 'asd');
    headers.set('token2', 'lol');
     if (localStorage.getItem('token1')) {
     headers.set('token3', 'gosh');
     }
    }
    const headers = new Headers();
    this.myLovellyHeaders(headers);

4 个答案:

答案 0 :(得分:13)

Angular 4.3 +

在Interceptor中设置多个标题:

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

import {environment} from '../../../../environments/environment';

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

    const headers = new HttpHeaders({
      'Authorization': 'token 123',
      'WEB-API-key': environment.webApiKey,
      'Content-Type': 'application/json'
    });


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

    return next.handle(cloneReq);
  }
}

答案 1 :(得分:9)

我的代码使用以下方法添加新标头以用新值替换以前的值:

headers: req.headers.set('token1', 'asd')
.set('content_type', 'asd')
.set('accept', 'asd')

答案 2 :(得分:8)

新的HTTP客户端使用不可变的标头对象。您需要存储对前一个标头的引用以改变对象:

 myLovellyHeaders(headers: Headers) {
     let p = headers.set('token1', 'asd');   
     p = p.set('token2', 'lol');
     if (localStorage.getItem('token1')) {
        p = p.set('token3', 'gosh');
     }

请参阅Why HttpParams doesn't work in multiple line in angular 4.3以了解您需要存储对返回值的引用的原因。

标题也是一样:

export class HttpHeaders {
  ...
  set(name: string, value: string|string[]): HttpHeaders {
    return this.clone({name, value, op: 's'});
  }

  private clone(update: Update): HttpHeaders {
    const clone = new HttpHeaders();
    clone.lazyInit =
        (!!this.lazyInit && this.lazyInit instanceof HttpHeaders) ? this.lazyInit : this;
    clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);
    return clone;
  }

要了解有关拦截器背后力学的更多信息,请阅读:

答案 3 :(得分:6)

要附加到克隆请求的现有标头(如在HTTP拦截器中),下面的代码可以工作(使用Angular 5.x)。在下面的例子中,它附加到现有的头文件(在我的情况下包括Angular自动包含的XSRF-TOKEN cookie)和一个存储在sessionStorage中的JWT授权令牌:

DataFrame