Angular2 - adding the authentication token to request headers

Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact that the function responsible for fetching the token operates asynchronously. As a result, the HTTP get request is triggered before the token can be properly inserted into the header.

Is there a more effective approach to ensure that the HTTP get request waits until the token retrieval process is complete?

Sample Code:

getData(query: Vehicle): Observable<ResultWrapper> {
        this.spinnerService.show();
        return this.http
            .get(`${this.myService.apiEndpoint}/vehicles?name=${query.make}`,
                { headers: this.myService.getHeaders() })
            .map(this.extractData)
            .catch(this.exceptionService.catchBadResponse)
            .finally(() => {
                this.spinnerService.hide();
            });
    }

myService:

getHeaders(): any {
    // This function involves an asynchronous JavaScript method call
    this.config.getToken(function (responseData) {
        if (!responseData.error) {
            responseData.headers.append('Authorization', "Bearer " + responseData.token);
            return responseData.headers;
        });
}

Answer №1

There is definitely a solution for this issue, but there might be a more efficient way to address it. One option could be to have your Auth service (referred to as myService) store a cached token and provide it to the requester using a method like getAccessToken() which would retrieve the token from localStorage.getItem('auth_token'). Then, you can set up something similar to

let headers = new Headers({ 'Authorization': 'Bearer ' + this.myService.getAccessToken() });

In this setup, you would just need to handle errors when making the getData call (specifically code 401) in case the token expires, and simply request a new one.

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

What is the most effective method for handling numerous HTTP requests upon the initialization of an application?

Within my Angular application, I am facing the challenge of executing multiple (6) HTTP requests from different sources during initialization. Currently, I am using app_initializer and promise.all() to achieve this. However, the issue lies in the fact that ...

Encountering an issue with importing mongoose models while trying to create a library

I've been working on creating a library of MongoDB models and helper classes to be shared as an npm module with the rest of my team. However, I'm facing an issue with the main code that I import from lib MongoConnector which processes configurati ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Angular: The type AbstractControl<any> cannot be assigned to type FormControl

I am working with a child component that includes an input tag <input [formControl]="control"> component.ts file @Input() control: FormControl; In the parent component, I am using it as follows: <app-input [control]="f['email ...

When a MatFormFieldControl both implements ControlValueAccessor and Validator, it can potentially lead to a cyclic

I am attempting to develop a custom form control by implementing MatFormFieldControl, ControlValueAccessor, and Validator interfaces. However, I encounter issues when including NG_VALUE_ACCESSOR or NG_VALIDATORS. @Component({ selector: 'fe-phone-n ...

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...

Using constant variables as arguments in functions in TypeScript

While learning about TypeScript, I encountered some confusion regarding how it handles const variables. Let's consider a scenario where I define an interface for a number: interface MyNumber { value: number; } If I then create a constant MyNumbe ...

HttpErrorResponse: unexpected internal server error

Just getting started with Angular 6. I created a post service using Spring Boot, and it works perfectly when tested with Postman. But testing it in a web browser results in the following error: HttpErrorResponse {headers: HttpHeaders, status: 500, statusT ...

Angular 2 tutorial on best practices for using const variables in your code base

The Angular Style Guide for angular2 suggests spelling const variables in lower camel case. It mentions that the practice of using UPPER_SNAKE_CASE for constants was more common before modern IDEs made it easier to identify constant declarations. TypeScrip ...

Adjust the class of a component

This is the HTML code for my home component: <button (click)="onClick('Hello')" [ngClass]="{'positive': connectedToWWE, 'negative' : !connectedToWWE}"> Hello! Click Me! </button> This is the Ty ...

Tips for extracting elements from an HTML document using Angular

I seem to be facing a small issue - I am trying to develop a form using Angular. Below is my HTML: <form [formGroup]="requeteForm" (ngSubmit)="ajouter()" *ngIf=" tables!= null"> <div class="form-group&quo ...

Mapping the changes in the checkbox of a material tree node

Check out this demo on StackBlitz: Tree View I'm having issues with the tree not displaying as desired. I would like it to look like this: Manager Sublist Manager 1 Manager 2 Manager 3 Could you please review and provide some advic ...

Is it possible to configure a custom timezone for the Angular Material datepicker feature?

I am currently working on an Angular 7 application and I have encountered a challenge with the date field. In this particular field, I am utilizing the Angular Material Datepicker input. However, I have noticed that the datepicker automatically captures th ...

Address aliases in the webpack configuration file

When utilizing webpack, it is possible to write the configuration file using TypeScript. However, it is crucial to ensure that any alias paths present in the config file are resolved to their mapped paths. It should be noted that this pertains specificall ...

The functionality of Angular 2 md-radio buttons in reactive forms seems to be hindering the display of md-inputs

Currently, I am following the instructions for implementing reactive form radio buttons on a project using Angular 2.1.2 and Google's MD-alpha.10 Atom-typescript shows no errors in my code. However, when testing the application, I encountered the foll ...

The properties in Typescript, specifically 'value', are not compatible with each other

I've encountered an error while working on a TypeScript project with React Context. The error message states: Argument of type 'Context<{}>' is not assignable to parameter of type 'Context<IsProductContext>'. The type ...

Certain Material-UI components appear to lack proper styling

I found a tutorial on how to incorporate material UI into my app at this link: https://mui.com/material-ui/getting-started However, I noticed that some components are not styled as expected and customizing the theme seems to have no effect... This is how ...

Establish a connection between an Angular Docker container and an Asp.Net container

A program was developed with three main components: a database (MS SQL Server), backend (Asp.Net Core), and frontend (Angular 8). The program is run using docker-compose: services: sqlserver: image: mcr.microsoft.com/mssql/server:2019-latest ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

Utilizing Express for Angular serverside rendering: Best practices explained

I attempted to utilize Angular's Server Side Rendering and encountered difficulties with a very basic scenario. Challenges Challenge 1 Expected outcome : Using express to simplify the angular app by only returning a "welcome object" Actual outcome : ...