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

Exciting updates revealed upon new additions (angular)

I'm working with three components in my Angular application: app.component, post-create.component, and post-list.component. Let's take a look at the structure of these components: <app-header></app-header> <main> <app-post-c ...

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

Managing enum types with json2typescript

After receiving a JSON response from the back-end that includes an Enum type, I need to deserialize it. The JSON looks like this: { ..., pst:['SMS','EMAIL'], ... } In Typescript, I have defined my enum class as follows: export enum Pos ...

I require all of this to be brought back as one complete entity. If, for instance, the object is given the value 10/26, it should be interpreted as part of the input

I am facing an issue with my Angular + .NET Application where the search method is not recognizing a specific ConsumerUnit when the input includes a / character. Currently, if I input something like 10/2689123, the application treats the / as part of the ...

Generating Graphql types for React using graphql-codegen when Apollo Server is in production mode: A step-by-step guide

Everything functions perfectly when backend mode is set to NODE_ENV: development, but in production mode I encounter an error with graphql-codegen: Error on local web server: Apollo Server does not allow GraphQL introspection, but the query contains _sc ...

Error encountered in Angular10: XHR request for POST failed due to browser blocking HTTP Request to a domain with a similar name

I am encountering an issue with my webpage that consists of a Django REST API and an Angular 10 Frontend SPA. Normally, I can successfully send GET, POST, PUT, and DELETE XHR Requests to my backend without any problems. However, there is a specific API End ...

Managing Visual Studio Code Extension Intellisense: A Guide

I am looking to create an extension I recommend using "CompletionList" for users. Users can trigger completion by running "editor.action.triggerSuggest" The process of my extensions is as follows: Users input text If they press the "completion command," ...

Displaying time in weekly view on the Angular 4.0 calendar

I've integrated the library into my Angular application to manage calendar events display and creation. The app features a monthly, weekly, and daily view option for users. However, I noticed that in the weekly view, only the dates are shown without ...

Enhancing the Angular Community Library Project

I am currently working on an Angular project version 7.1 and have developed 2 angular libraries that are being used in the project. In order to upgrade my project from version 7.1 to 8.2, I used the following command: ng update @angular/cli@8 @angular/core ...

Error in Angular 4: Unexpected 'undefined' provided instead of a stream

I encountered an issue while attempting to make a HTTP Post request. The error message I received is as follows: auth.service.ts?c694:156 Something went wrong requesting a new password, error message: You provided 'undefined' where a stream ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

Priority of Typescript TypeRoots

After extending a class from an npm package with additional type definitions, I noticed that my custom definitions are taking lower priority than the ones coming from node_modules. Is there a way to adjust the TypeScript definition priority using the typeR ...

Top method for managing dates in TypeScript interfaces received from the server

After encountering the issue detailed in Dates in a Typescript interface are actually strings when inspected I faced a challenge while defining a TypeScript interface for a response from a server API, particularly with a Date parameter. The data arrived a ...

Is it possible to implement an authentication guard in Angular and Firebase to verify if the user is currently on the login page?

My Current Tools Using Angular and Firebase My Objective To implement an Auth Guard that can redirect users based on specific conditions Current Progress I have set up an auth guard on various components which redirects users back to the login page ...

Version 7.0.0 of Angular has not been properly set up on

Seeking guidance on installing angular version 7.0.0, I followed these steps: npm i -g @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adcec1c4ed9a839d839d">[email protected]</a> Unfortunately, an error ...

Is it possible to initiate a request action in both the constructor and ngOnInit method?

I am facing a situation where I need to trigger a request action from both the constructor and ngOnInit functions in order to load data. However, I have noticed that on the second call, one of the dispatch actions is not being invoked and the data remains ...

Encountering trouble with Angular material library following upgrade to Angular 6

Upon attempting to compile the application, I encountered the following error: ERROR in src/app/app.module.ts(15,5): error TS2304: Cannot find name 'MatToolbarModule'. src/app/app.module.ts(16,5): error TS2304: Cannot find name 'MatSidenavM ...

Angular | Boosting performance with asset chunking

This particular inquiry mirrors 92% chunk asset optimization - webpack. However, a satisfactory solution has yet to be found. Typically, I utilize ng serve or nmp start to initiate my service locally and it functions correctly. However, on an EC2 instance ...

Return the previous value if the filter function returns false in RxJs

In an attempt to optimize performance and reduce unnecessary requests to the server, this code checks if values exist in the store before making additional requests. While the overall logic functions correctly, there is an issue where if the filter returns ...