Search code examples
angulartypescripthttp-headershttpclient

How to delete a header for a given name in angular?


In my app, I'm doing multiple HTTP requests. All of them need an authentication header with an access token (and some other header values). I defined in a header variable of type HttpHeaders (see code#1) to use it like this.http.get(this.myUrl, { headers: this.headers}).
In my case, the token has to be refreshed over time and I want to change the header to contain the newest token.

In my code, I have a refresh function which should refresh the token and replace the old token in the HTTP header with the new one.
My first approach was to use the provided set() method(see code#2). This added a new value to the header and did not replace it (I now had two vales of Authorization).
My second approach was to use the delete() method(see code#3) and delete Authorization and then use the append() method and a new one. This caused a similar result.
My last approach was to just use the delete() method(see code#4).


code samples

code#1:

headers = new HttpHeaders()
  .set('Content-Type', 'application/json')
  .set('Accept', 'application/json');

code#2:

this.headers = this.headers
  .set('Authorization', 'Bearer ' + access_token);

code#3:

this.headers = this.headers.delete('Authorization');
this.headers = this.headers.append('Authorization','Bearer ' + access_token);

code#4:

this.headers = this.headers.delete('Authorization','Bearer ' + access_token);


results

I expected that either the value of the header ({'Authorization', 'Bearer ' + access_token}) gets replaced (1st approach). The actual result was that it just got appended:

{"Authorization", "Bearer access_token-old"}
{"Authorization", "Bearer access_token-new"}

And for the second approach, I expected to delete and appending a new value which caused to still adding two values:

{"Authorization", undefined}
{"Authorization", "Bearer access_token-new"}

My last approach caused the same output as in my first approach, instead of just replacing the value.

Do you know any method to just replace the access_token/value in {'Authorization','Bearer ' + access_token}?


Solution

  • I managed to find an easy workaround to fit my case:

    1. I'm defining the header:
    headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Accept', 'application/json');
    
    1. Every time I need to refresh the token I do this:
    this.headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Accept', 'application/json')
      .set('Authorization', 'Bearer ' + access_token');
    


    But If anybody has an idea how to do it with set(), append(), delet(), etc. I would love to hear it.