Removing a header in angular based on a specific name - a step-by-step guide!

Within my application, I am making multiple HTTP requests that all require an authentication header with an access token (along with other header values). I have defined a header variable of type HttpHeaders (refer to code#1) to be used as follows:

this.http.get(this.myUrl, { headers: this.headers})
.
In my scenario, the token needs to be refreshed periodically and I want to update the header with the latest token.

In my code, there is a refresh function that is responsible for obtaining a new token and replacing the old token in the HTTP header with the updated one.
Initially, I attempted to utilize the provided set() method (see code#2). However, this approach resulted in adding a new value to the header instead of replacing it, leading to duplicates.
Subsequently, I tried using the delete() method (see code#3) to remove the Authorization value first and then using the append() method to insert the new token. Unfortunately, this also did not achieve the desired outcome.
My final attempt involved solely using 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

My expectation was that the value of the header

({'Authorization', 'Bearer ' + access_token})
would be replaced (in the 1st approach). Instead, the actual result showed that it was just appended:

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

As for the second approach, the goal was to delete and append a new value, however, it still ended up adding two values:

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

The last approach yielded the same output as the first approach, rather than simply replacing the value.

Is there any method available to seamlessly replace the access_token/value in

{'Authorization','Bearer ' + access_token}
?

Answer №1

Check out this solution

const httpHeaders: HttpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.set('Accept', 'application/json');
httpHeaders = httpHeaders.set('Accept', 'application/json');
httpHeaders = httpHeaders.set('Authorization', `Bearer ${access_token}`);

Answer №2

I discovered a simple solution that worked perfectly for my situation:

  1. First, I define the header:
headers = new HttpHeaders()
  .set('Content-Type', 'application/json')
  .set('Accept', 'application/json');
  1. Whenever I need to refresh the token, I follow this step:
this.headers = new HttpHeaders()
  .set('Content-Type', 'application/json')
  .set('Accept', 'application/json')
  .set('Authorization', 'Bearer ' + access_token');


If anyone knows of a different method using set(), append(), delete(), etc., please share with me!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a TypeScript error when using Redux dispatch action, specifically stating `Property does not exist on type`

In my code, there is a redux-thunk action implemented as follows: import { Action } from "redux"; import { ThunkAction as ReduxThunkAction } from "redux-thunk"; import { IState } from "./store"; type TThunkAction = ReduxThunk ...

There are no versions available for Angular NPM that match [email protected]

Here is the contents of my .npmrc file: registry=https://pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/ always-auth=true After deleting node_modules and attempting to install the packages, I encountered the follo ...

Component-specific provider registration in Angular

Registering a provider at the component level results in a new instance of the service being created for each new instance of that component. The service becomes an instance variable of the component object, making it a dependency. This dependency can be i ...

Steps for Creating a User in the Meetup API

Exploring the functionalities of the meetup API has sparked my interest in incorporating it within my application to facilitate user creation, group joining, event hosting, and more. I am uncertain about the feasibility of this endeavor. Situation Imagi ...

Is there a way to showcase Images or Stars in a Material Angular Form?

I have a form where the rating is displayed using star images, but it is stored as a number in string format on the backend. While experimenting, I am trying to figure out the best way to achieve this. Currently, this is what I have: https://i.sstatic.net ...

Tips for Promoting Content Using Offcanvas Navigation Menu

I am currently working on an Angular 12 project that incorporates Bootstrap 5 and NGX-Bootstrap. I am interested in developing a side navigation bar that is initially active but can also be collapsed. I wonder if this could be achieved using the Offcanvas ...

"iOS users have reported that notifications from Firebase have mysteriously ceased to

Yesterday evening, I was experimenting with Push Notifications from Firebase on my iOS application and everything was functioning correctly. I successfully sent a notification from a Cloud Function to a specific FCM token. However, this morning, notificat ...

I must determine whether to display an angular component based on the user's selection

To display the aprs-attachments only when the 'PCCL (Production)' environment is selected in the hostSection/environments, you need to modify your code. Below is the current setup of the code. You need to specify the *ngif statement to show the a ...

Adding a class to the current li element without affecting its siblings in Angular 2

I am dealing with a structure that looks like this: <div> <ul> <li> <ul> <li>Option 1</li> <li>Option 2</li> <li>Option 3</l ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

Having trouble correctly displaying a form with nested form array within a form group

I am working with a form group that contains nested form groups and a form array: ngOnInit() { this.form = this.fb.group({ dropDownOptions: this.fb.group({ items: this.fb.array([this.createItem()]) }) ...

Manipulate MySQL data in Node.js by storing it in a variable

Struggling to grasp the concepts of nodeJS/typescript and how to effectively save database query results into variables for return. Seeking assistance to solve the problem faced: Here is a method snippet that needs help: public getAllProducts(): ProductA ...

How can Bootstrap 4 be utilized to achieve a responsive height on a single page application with no scrolling?

Embarking on the journey of responsive website design as a beginner in front end development, I am currently working on creating a basic angular chat application with bootstrap. Keeping responsiveness in mind throughout the design process is my goal, but I ...

Changing the color of an input field in Angular Material to red

Below is an example of Angular code where the mat-form will turn red automatically if no value is entered. <mat-form-field> <input matInput placeholder="Enter your email" [formControl]="email" required> </mat-form-field> In the scenar ...

Preventing access to the login portal

Currently, I am exploring the most effective method to prevent or redirect users from accessing the login page if they are already authenticated. I am currently working on a React project with TypeScript. What would be the optimal approach to achieve thi ...

Find the combination of all potential function outputs

I'm trying to figure out why the compiler doesn't infer A as a union type like string[] | number[] when it fails. Instead, A is inferred as the first return value, which in this case is string[]. Is there a solution to this issue? const define = ...

What is preventing me from adding members to an imported declaration?

Currently, I am attempting to include a constructor in an imported declaration. As per the information provided in the documentation, this should be feasible. (Refer to Chapter Adding using an interface) Below is the code snippet that I have used: import ...

What causes JSON object properties to be null when sent as an Angular request to the Spring Java backend?

When sending a Post request from both the Angular Application and Chrome Poster, I encountered an issue. Using Chrome Poster, I provided the following information: URL: http://localhost:8080/rentapp/policy Header: content-type application/json Conte ...

JavaScript modules in Node.js do not support non-relative imports properly with Typescript

My goal is to develop a straightforward TypeScript script that utilizes ES modules, runs with node, and includes sourcemaps for debugging purposes. Here's the script that runs with node test.ts: import foo from './foo' //import bar from &a ...

Guide to dynamically adjusting a DOM element's size during execution

Within my Angular 2 project, I am attempting to adjust the size of a specific DOM element by using its id. Despite setting the height as shown below, I do not see any visible changes taking place. What additional step do I need to take in order for this ...