Generate a series of HTTP requests using an HTTP interceptor

Is it possible to initiate an http request before another ongoing http request finishes (For example, fetching a token/refresh token from the server before the current request completes)?

I successfully implemented this functionality using Angular 5's httpInterceptor, but I am facing challenges with Angular 7.

intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
            return Observable.fromPromise(this.handleAccess(request, next))
              .map(response => {
                console.log(response);

                this.globalService.showOrShowloadingModel("hide");
                return response;
              })
              .catch(error => {
                console.log("HTTP error", error);  
                return Observable.of(error);
              });
}

private async handleAccess(request: HttpRequest<any>,next: HttpHandler): Promise<HttpEvent<any>> {
        //logic to trigger token API
        await this.globalService.validateAccessToken();
        return next.handle(request).toPromise();
}

Answer №1

To efficiently handle multiple HTTP requests simultaneously, consider using ForkJoin in your codebase. First, ensure you import ForkJoin from rxJs library. Next, implement the following code snippet:

forkJoin(
      this._myService.makeRequest('Request One', 2000),
      this._myService.makeRequest('Request Two', 1000),
      this._myService.makeRequest('Request Three', 3000)
    )

By executing this, all three requests will be initiated concurrently for improved performance.

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 type of HTML tag does the MUI Autocomplete represent?

Having trouble calling a function to handle the onchange event on an autocomplete MUI element. I've tried using `e: React.ChangeEvent`, but I can't seem to locate the element for the autocomplete component as it throws this error: The type &apos ...

Troubleshooting native web worker issues in Angular 11 - Addressing the Element Bug

After upgrading Angular to version 11, I encountered issues with utilizing web workers for heavy data processing in my project. Previously, I used webworkify-webpack (https://www.npmjs.com/package/webworkify-webpack), but it stopped working post-migration. ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

Having difficulties launching plnkr for Angular 4

I have a plunger code here that is meant to display a child Component. Here is the HTML inside the child component: <div> <h3>I am the Child component</h3> </div> Take a look at the Plnkr code here. However, when I run ...

Ways to fix the perpetual cycle in adal-angular4 following authentication redirect

I have been working on an Angular 8 application that utilizes Microsoft Azure Active Directory authentication with adal-angular4. I've successfully set up an ASP.NET Core API linked to a client app on Azure. To configure Active Directory, I referred ...

Encountered an issue with formControlName being undefined during the render process in Angular 2

I encountered an issue while implementing Reactive form validation following the official Angular documentation. The error message "username not defined" is causing trouble in my project. Here's the detailed error: Error: Uncaught (in promise): Error: ...

What is the best way to implement multiple templates for a single component?

Is there a way to configure my Home Component based on the user's role? For instance: If the employee is an admin, then the home component should load the template URL designed for admins. Likewise, if the employee is a cashier, then the home compo ...

The ng build command encounters a failure (module cannot be found) when running in a docker environment on Ubuntu, while it successfully runs

I'm facing an issue that I can't quite pinpoint whether it's related to docker, Ubuntu, or node/npm. Here are all the details I have: Although there are known causes for this module error, none of them explain why it works on various Window ...

Establishing a pair of separate static directories within Nest

I am looking to utilize Nest in order to host two static applications. Essentially, I have a folder structure like this: /public /admin /main Within my Nest application, I currently have the following setup: app.useStaticAssets(join(__dirn ...

No slides are available for display, resulting in the ngx-owl-carousel console message indicating that the carousel will not be re-rendered

I've been attempting to integrate ngx-owl-carousel-o into my Angular 11 application, but I keep encountering the following message in my console: There are no slides to show. As a result, the carousel will not be re-rendered. Unfortunately, nothing ...

Utilizing Angular: Integrating the Http response output into a map

I have a situation where I am making multiple HTTP calls simultaneously from my Angular application. The goal is to store the responses of these calls in a Map. data: Map<number, any> = new map<number,any>(); --------------------------------- ...

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

Display JSON element in Angular only once

Below is the code snippet: <ion-content padding> <h1>Datum: </h1> <ion-list> <ion-item *ngFor="let u of tecaj"> <h2>{{u.datum}}</h2> <h2>{{u.drzava}} | {{u.valuta}}</h2> ...

Starting object arrays in Angular 6 using ES6

As someone who is just starting out with javascript, I have encountered a challenge with a nested class structure. Specifically, I am looking to initialize an array of EventDate objects and assign it to 'this.dates' within the CustomerEvents cons ...

Is it possible to create dynamic meta tags in Angular that will appear in a Twitter-style card preview?

My project involves building a dynamic website using a Java app that serves up a REST-ish JSON API along with an Angular9 front end. A key requirement is the ability to share specific URLs from the app on platforms like Twitter and Slack, which support Twi ...

How to retrieve start and end time values from dropdown options using formArray in Angular 8

Within my form group, I have start time and end time select options in a form array. My goal is to dynamically update the end time array based on the selected start time. <div [formGroupName]="skillIndex"> Start at: <select ...

Error handling in Angular2 RxJS when using switchMap

Is there a way to properly manage errors that occur when calling this.authService.refreshToken()? How can I handle errors within the switchmap block or implement error handling in this scenario? post3(endpoint: string, body: string) : Observable<any& ...

Using Typescript alongside Angular 1.6 and browserify for your development needs

Currently navigating the world of working with Angular types in TypeScript and bundling code using Browserify. After following a TypeScript guide related to Gulp, I utilized npm to install the Angular types and put together this simple ts file. import * a ...

Retrieving the innerHTML or innerText of a structural DOM element generated by *ngFor in Selenium

Having trouble accessing the innerHTML/innerText of a structural DOM element, only getting a commented element instead of the child elements. <div class="snap-box"> <label class="snap-heading">Recommendations</label> <div class="r ...