Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interceptor Angular 4.3 - Set multiple headers on the cloned request

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 Interceptor logic:

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

I have, now, two ways to add my headers in this request:

Example:

headers?: HttpHeaders;

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

setHeaders?: {
   [name: string]: string | string[];
};

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

How can I add multiple headers conditionally on this request? Same to what I used to do with the Header Object:

 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);
like image 310
39ro Avatar asked Aug 07 '17 17:08

39ro


People also ask

Can I have multiple HTTP interceptors in angular?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.

How many types of interceptors are there in angular?

In this post, we cover three different Interceptor implementations: Handling HTTP Headers. HTTP Response Formatting. HTTP Error Handling.


3 Answers

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);
  }
}
like image 198
non4me Avatar answered Oct 20 '22 17:10

non4me


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')
like image 42
Enayat Avatar answered Oct 20 '22 18:10

Enayat


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
like image 12
Max Koretskyi Avatar answered Oct 20 '22 19:10

Max Koretskyi