How can Angular developers properly implement token refreshing in their applications?

Recently, I've been struggling with implementing a logic in my code.

I have a specific requirement:

Whenever there is a signed request (signed - means it has a JWT token for authenticated users) made to the API backend, the API backend may respond with a 401 JWT Token Expired error. In such a scenario, I want to trigger another request to refresh the JWT token and then reattempt the original request if successful. If unsuccessful, I need to redirect to the login page.

The current issues I'm facing with this implementation are:

1) The refreshToken() function is located inside ApiService, but I believe it should be in AuthService as it is related to authentication. However, moving the method to AuthService would require me to inject AuthService into ApiService, leading to a circular dependency issue. Additionally, I am unsure how to pass arguments in the constructor for AuthService to make the .super(args) call.

2) My code is currently not functioning properly due to this part:

this.refreshToken().toPromise().then(() => {
    if (request.data) {
      console.log('POST');
      return this[request.method](request.endpoint, request.data);
    } else {
      console.log('GET');
      return this[request.method](request.endpoint);
    }
  });

Since refreshToken is asynchronous, I cannot directly call the original method. How can I address this issue?

Here is an example of my code:

DataService

// Code for DataService
// ...

ApiService

// Code for ApiService
// ...

TendersService

// Code for TendersService
// ...

AuthService

// Code for AuthService
// ...

Answer №1

Consider using dependency injection instead of service inheritance. It's a good idea to move methods like "refreshToken" to the AuthService and also transfer the "handleError" method there to handle authentication errors. This way, you won't need to inherit from your ApiService anymore, as its purpose may not be entirely clear.

In DataService, you can inject AuthService instead of inheriting it and update request headers for authentication. Separating AuthService from DataService is preferable in my opinion.

You can find a useful example on github here. For a comprehensive guide, check out this link: Link.

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

Use Typescript in combination with React/Redux to showcase a dynamic table on the

Looking to create a React TypeScript Redux application that showcases a table using an API endpoint provided at https://example.com/users The goal is to construct a table with 4 columns: Name, Email, City, and Company, utilizing the API response to popula ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

`"Unable to execute the 'ng build --env=prod' command"`

I have a JavaScript website that I need to rebuild with some changes I made. In order to build the application, I was instructed to run this command from the source files directory: ng build –env=prod However, when I try to do so, I keep encountering t ...

After running `npm uninstall -g angular-cli`, I thought I had successfully removed angular-cli from my system. To my surprise, when I checked `ng --

What's the deal here? I uninstalled angular-cli globally on my laptop by running npm uninstall -g angular-cli, and now it's gone. But on my desktop, I can still use ng --version even after removing angular-cli globally. Any idea what's ha ...

Remap Objects Function with Correct Return Data Type

After receiving data from another source via a post request in a large object, I need to extract specific fields and organize them into more precise objects with some fields remapped before inserting them into a database. Currently, I have a working solut ...

Having trouble with NextJS TypeScript and the randomUUID?() function? If you're seeing the error TS2386 that says "Overload signatures must all be

In my project setup, I have a mono-repo structure utilizing Lerna for managing 2 NextJS projects and 1 shared project. I recently attempted to integrate typescript. The NextJS projects seem to be functioning correctly (following the documentation), but I ...

Loading a view in Ionic2 with Angular2 after a successful subscription

After completing an http post request, I want to navigate to the next view in my app. Here is a breakdown of the three services I am using: The server service handles generic http calls such as get and post requests. The city service stores a list of ...

What is the location of the Typescript project path in Visual Studio 2015 Cordova?

In my development journey, I decided to create a Typescript blank Cordova project within Visual Studio 2015. After adding a small test bit of ts code... function onResume() { // TODO: This application has been reactivated. Restore application st ...

Choosing a particular checkbox with changing identifiers in Cypress: A guide

Having trouble selecting a specific checkbox without a distinct identifier? The ID keeps changing, so using it to target the checkbox directly isn't an option. Check out this image of the checkbox: https://i.stack.imgur.com/kwzAS.png This particular ...

Step-by-Step Guide on Incorporating leaflet-control-geocoder into Angular 12.x

After successfully integrating Leaflet into Angular 12 using the following commands: npm install leaflet npm install @asymmetrik/ngx-leaflet npm install --save-dev @types/leaflet I made sure to include the styles: ./node_modules/leaflet/dist/leaflet.css i ...

Disable TS4023 error in TypeScript: Unable to name external module "xyz"

//custom-slice.js import { createCustomSlice } from '@my/data-toolkit'; /* ***********************For Managing all the divisions data****************************** */ export const divisionDataSlice = createCustomSlice({ name: 'divisionda ...

What is the best way to utilize ngStyle in combination with Interpolation?

Within my application, I am faced with a challenge involving two slide bars that generate values ranging from 1 to 100. Based on these generated values, I aim to adjust the margin of a div element in accordance with the percentage output. Despite conductin ...

How can I exclude the 'node_modules' directory but still include specific subfiles in the tsconfig file for TypeScript?

My tsconfig file is structured as follows: { "compileOnSave": false, "compilerOptions": { "module": "es2015", "target": "es2015", "sourceMap": true, "jsx": "react", "allowSyntheticDefaultImports": true, "noImplicitAny": false, ...

Is it possible to streamline the process of importing all CommonModule modules during bootstrap with the new standalone feature in Angular?

I've recently started experimenting with Angular's standalone feature and module-less approach. However, I'm having trouble finding the information I need. From what I understand, in a standalone component you have to import any directives/ ...

Cancel promise chain after action dispatch (rxjs)

My goal is to achieve the following: this.jobManager .queue( // initiate a job ) .then( // perform additional actions, but stop if `ABORT` action is dispatched before completion ) .finally( // carry out necessary ...

What is the optimal approach for building a frontend using Angular and Microservices architecture with .NET Core?

Previously, we have worked on projects using a monolithic architecture with .NET Framework and MVC. Now, we are transitioning to Angular+NET Core. There are two approaches I am considering: -The first option involves creating the frontend using Angular CL ...

Encountering an Object Type Unknown error while working with Typescript and React

I am currently working on building a chatbox in React using TypeScript and Firebase. Below is the code for my Room and Message components: function ChatRoom() { const messagesRef = firestore.collection('messages'); const query = messagesRef.o ...

Issue concerning the Bootstrap version, transitioning from Bootstrap 3 to Bootstrap 4

Upon initially installing bootstrap version "bootstrap": "^3.3.7",, everything was functioning properly, except for the inability to utilize a card component. For example: <div class="card" style="width: 18rem;"> <img class="card-img-top" src= ...

The error encountered during parsing the module for Next.js, Webpack, and TypeScript files (.ts, .tsx) was due to an unexpected token

Here is the content of my next.config.mjs file: export default { webpack: (config) => { // Find rules that includes current directory const rulesWithCurrentDir = config.module.rules.filter((rule) => rule.include && rule.include.incl ...

The 'locale' parameter is inherently assigned the type of 'any' in this context

I have been using i18n to translate a Vue3 project with TypeScript, and I am stuck on getting the change locale button to work. Whenever I try, it returns an error regarding the question title. Does anyone have any insights on how to resolve this issue? ...