Interceptor Angular 4.3 - Set multiple headers on the cloned request

。_饼干妹妹 提交于 2019-11-29 05:30:06

The new HTTP client works with immutable headers object. You need to store a reference to the previous headers to mutate the object:

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

See Why HttpParams doesn't work in multiple line in angular 4.3 to understand why you need to store the reference to the returned value.

It's the same thing for headers:

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

To learn more about mechanics behind interceptors read:

Angular 4.3+

Set multi headers in 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);
  }
}

My code worked with the following approach to add new headers to replace previous values by new values:

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

To append to the existing header of a cloned request (like in an HTTP Interceptor), the code below works (using Angular 5.x). In the case below, it appends to the existing header (which in my case includes the XSRF-TOKEN cookie automatically included by Angular) with a JWT Authorization token stored in sessionStorage:

export class TokenInterceptor implements HttpInterceptor {

    constructor() { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let headers = request.headers
            .set('Content-Type', 'application/json')
            .set('Authorization', `Bearer ${sessionStorage.getItem('authToken')}`);

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

        return next.handle(cloneReq);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!