Exploring Angular 4.3's HTTP Interceptor Retry功能

As I delve into my first attempt at coding, I find myself faced with the challenge of capturing 401 errors using HttpInterceptor. My goal is to generate a new auth token based on a certain condition and then retry the process with that token in place. However, I am running into an issue where the retry happens before the new auth token is actually created. Here's a snippet of my code:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {

    return next.handle(request).catch(error => {

        if (error.status === 401) {
            console.log('401 error');

            let refreshToken = localStorage.getItem('refresh_token');

            this._refreshTokenService.getRefreshToken(refreshToken).subscribe(
                refreshToken => {
                    if (refreshToken != null) {
                        console.log('valid refresh token')

                        console.log(localStorage.getItem('auth_token'));

                        this._userService.logout();

                        let email = localStorage.getItem('profile_email');

                        this._userService.autoLogin(email)
                            .subscribe(
                            result => {
                                if (result) {
                                    console.log('new auth token created');
                                    let auth_token = localStorage.getItem('auth_token');
                                    request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${auth_token}`) });
                                }
                            });
                    }
                    else {
                        console.log('invalid refresh token');
                    }
                });

            return next.handle(request);
        } 
        else {
            console.log(error.status);
        }
    });
}

While navigating through Typescript syntax, I've come to realize that I need to ensure the retry only takes place once the new token has been successfully generated. However, I'm uncertain about the specific syntax required to achieve this. Any guidance or assistance on this matter would be highly appreciated!

Answer №1

Unfortunately, I am unable to respond in the comment section at this time. It seems that the main focus here is on creating a chain of Observables.

Essentially, all operations you execute before the final return next.handle(request); are processed prior to Angular making the HTTP request. However, anything within

this._refreshTokenService.getRefreshToken(refreshToken).subscribe()
will be handled asynchronously.

The recommended approach for chaining your Observables is as follows:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
    return next.handle(request).catch(error => {
        return this._refreshTokenService.getRefreshToken(refreshToken).subscribe(
            refreshToken => {
                return next.handle(request);
            }
        );
    });
}

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

Utilizing Angular 2 to Fetch Data from API during Initialization

I'm currently facing an issue in my Angular service where I am attempting to call an API to retrieve user data based on the ID stored in localStorage. However, the API doesn't seem to be getting called at all. Can anyone provide assistance with t ...

Encountering Invalid Chai attribute: 'calledWith'

I am currently in the process of implementing unit tests for my express application. However, I encountered an error when running the test: import * as timestamp from './timestamp' import chai, { expect } from 'chai' import sinonChai f ...

Angular Elements generates compact, single-line HTML output

It's incredibly frustrating how browsers handle inline-block elements, creating invisible margins when placed side by side. You can experience this "bug" firsthand here: http://jsfiddle.net/8o50engu/ Interestingly, if these elements are on the same l ...

Guide on enabling the Access-Control-Allow-Origin feature for Angular 5 and Node.js:

After exploring various methods to include 'Access-Control-Allow-Origin', I have not been successful in resolving the issue. I am utilizing the @angular/common/http module with an external URL as a data source. However, when attempting to retrie ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Navigate back to the initial page in Ionic2 using the navpop function

I have an application that needs to guide the user step by step. While I am aware of using navpop and navpush for navigating between pages, I am unsure about how to use navpop to go back to the first page. Currently, I am attempting to pop() twice if ther ...

What causes a hyperlink to take longer to load when using href instead of routerLink in Angular 2+?

As I work on my web application using angular 2 and incorporating routes, I noticed a significant difference in loading speed based on how I link to another component. Initially, being new to angular, I used the href attribute like this: <a href="local ...

Remove focus from input field after submitting in a project using Typescript and React with react-hook-form

I'm currently working on a TS-React project and encountering an issue with barcode scanning in my inputs. I am using react-hook-form along with the useForm Hook. The form consists of one input-text field and a submit button, both within a global form. ...

npm installation raises concerns about unmet peer dependencies despite them being already satisfied

I recently completed an upgrade to the final release of angular 2 from rc-6. Transitioning through different beta/rc versions was smooth and without any complications. My package.json dependencies include: "dependencies": { "@angular/common": "2.0.0" ...

Presenting two arrays simultaneously creates angular duplicates

Encountering an issue while trying to display two arrays containing channel information: List of channels List of subscriptions that users have opted for. channels = [ { "id": 1, "name": "arte", "service&q ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...

After running a yarn build on a TypeScript project using a .projenrc.js file, make sure to include any packaged or additional text files in the lib folder, rather

After utilizing projen to create my typescript project, I followed these steps: mkdir my-project, git init, and npx projen new typescript. Additionally, I created two files - sample.txt and sample.js, along with the default file index.ts within the folder ...

Can you run both Angular 6 and AngularJS 1.6 applications on the same computer?

Trying to juggle the development of an Angular 6 app and an AngularJS 1.6 app on the same machine has posed a challenge for me. My current situation involves working on two projects simultaneously - one being a new project utilizing Angular 6 and Angular ...

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

The universe's cosmic energy is unable to retrieve uploaded documents

Struggling for days now with the issue of not being able to run any real tests using Karma. I can run basic sanity tests that don't require imports, but as soon as I try to import something from my app, I encounter this error: system.src.js:1085 GE ...

MUI version 5 with styled-components and ListItemButton: The specified property 'to'/'component' is not recognized

While transitioning from MUI v4 to v5, I encountered a hurdle: in v4, I utilized makeStyles(), but now aim to fully switch to styled(). Unfortunately, I am struggling to get Typescript to recognize a styled(ListItemButton)(...) with to= and component= attr ...

Pause before sending each request

How can we optimize the Async Validator so that it only sends a request to JSON once, instead of every time a letter is typed in the Email form? isEmailExist(): AsyncValidatorFn { return (control: AbstractControl): Observable<any> => { ...

Is there a way to establish a boundary for the forEach function in TypeScript?

In my web-based game, I use the forEach command to retrieve the team players in the lobby. However, for a specific feature in my game, I need to extract the id of the first player from the opposing team. How can I modify my current code to achieve this? T ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...