Interceptor Angular 4.3 - Set multiple headers on the cloned request

后端 未结 4 1691
夕颜
夕颜 2020-12-16 10:47

I just noticed that the Header Object that was possible to use in the previous HTTP RequestsOption is not anymore supported in the new Interceptor.

It\'s the new Int

4条回答
  •  不思量自难忘°
    2020-12-16 11:32

    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:

    • Insider’s guide into interceptors and HttpClient mechanics in Angular

提交回复
热议问题