Angular's HttpClient makes sure to wait for the HTTP requests to complete

Initializing arrays with the call this.Reload.All() is causing confusion and breaking the service due to multiple asynchronous calls. I am looking for a synchronous solution where each call waits for its response before proceeding to the next one. How can I achieve this?

Although my code is functioning correctly, the async nature of the calls is causing issues. How can I resolve this issue?

//Reload Reference Arrays
    RefVehicleTypes = [];
    RefClients = [];
    RefUsers = [];
    RefObjects = [];

//Reload Class:
    Reload = {
        DoCall : (pUrl, pArray, pResponse) => {
            this.HttpClient.get(pUrl).subscribe(
                (response: any) => {
                    this[pArray] = eval(pResponse);
                    console.log(pResponse + ' : ' + this[pArray]);
                }
            );   
        },
        All : () => {
            this.Reload.VehicleTypes();
            this.Reload.Clients();
            this.Reload.Users();
            this.Reload.Objects();
        },
        VehicleTypes : () => {
            this.Reload.DoCall(
                'http://...',
                'RefVehicleTypes',
                'response.dbVehicleType_response.view',
            );
        },
        Clients : () => {
            this.Reload.DoCall(
                'http://...',
                'RefClients',
                'response.dbClient_response.view',
            );
        },
        Users : () => {
            this.Reload.DoCall(
                'http://...',
                'RefUsers',
                'response.dbUser_response.view'
            );
        },
        Objects : () => {
            this.Reload.DoCall(
                'http://...',
                'RefObjects',
                'response.dbObject_response.view'
            );
        }
    }

NEW EDIT:

I attempted to replace the DoCall and All methods, but the issue persists. Please refer to the screenshot below for more information.

DoCall : (pUrl, pArray, pResponse) => {
    return new Promise((resolve, reject) => {
        this.HttpClient.get(pUrl).subscribe(
            (response: any) => {
                console.log('##############################' + pArray)
                console.log(this[pArray]);
                this[pArray] = eval(pResponse);
                console.log(this[pArray]);
                resolve();
            }
        )
    });
},
All : async () => {
    await this.Reload.VehicleTypes();
    await this.Reload.Clients();
    await this.Reload.Users();
    await this.Reload.Objects();
},

The screenshots show 3 refreshes where it seems like the async function All() is mixing up the arrays, causing delays in responses. The last refresh always works fine, indicating that previous responses might be getting overwritten by subsequent ones.

https://i.sstatic.net/UyvFD.jpg

Answer №1

Here is a potential solution for making synchronous calls in your code, although it hasn't been tested yet.

Loader = {
    MakeCall : (url, dataKey, responseData) => {
        return new Promise((resolve, reject) => {
            this.HttpClient.get(url).subscribe(
                (response: any) => {
                    this[dataKey] = eval(responseData);
                    console.log(responseData + ' : ' + this[dataKey]);

                    resolve();
                }
            );  
        }
    },
    QueueCalls : () => {
        this.Loader.Types().then(() => {
            return this.Loader.Clients();
        }).then(() => {
            return this.Loader.Users();
        }).then(() => {
            return this.Loader.Objects();
        }).then(() => {
            console.log("All calls completed");
        });
    },
    Types : () => {
        return this.Loader.MakeCall(
            'http://...',
            'VehicleTypes',
            'response.dbVehicleType_response.view',
        );
    },
    Clients : () => {
        return this.Loader.MakeCall(
            'http://...',
            'ClientsList',
            'response.dbClient_response.view',
        );
    },
    Users : () => {
        return this.Loader.MakeCall(
            'http://...',
            'UserList',
            'response.dbUser_response.view'
        );
    },
    Objects : () => {
        return this.Loader.MakeCall(
            'http://...',
            'ObjectList',
            'response.dbObject_response.view'
        );
    }
}

You can also use the following in newer JavaScript versions:

QueueCalls : async () => {
    await this.Loader.Types();
    await this.Loader.Clients();
    await this.Loader.Users();
    await this.Loader.Objects();
},

Both methods still utilize promises to handle asynchronous operations.

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

Exploring Angular's Animation Feature for HTML Element Movement

I'm currently using @angular/animations module to animate HTML objects and I want to move an object when a button is clicked. For example: * The object initially has top: 800px, left: 800px * Clicking the 'W' button should move the obje ...

Angular nested Tree is not appearing as anticipated

The tree structure I created using Angular Nested Tree component is not displaying the User Interface as expected. The words "fruit" and "vegetables" are overlapping with the text "expand more", making it difficult to read. Can someone help me fix this UI ...

Angular OAuth2 OIDC password reset process

Currently, I am integrating B2C into my Angular (8) application using angular-oauth2-oidc. I have successfully implemented sign-in and sign-out policies, as well as configuring the angular-oauth2-oidc service. However, when utilizing the standard Microsoft ...

Unlocking rotation on a single screen in a react native application can be achieved by altering

I attempted to use react-native-orientation within a webview in order to make it the only view that would rotate. import React, {useEffect} from 'react'; import { WebView } from 'react-native-webview'; import Orientation from "react-na ...

Unable to find '.file.scss' in the directory '../pages'

I am currently in the process of migrating my Ionic 3 app to version 4. However, I have encountered an issue where some pages are not recognizing the SCSS file from the TypeScript component. @Component({ selector: 'car-id', templateUrl: &apo ...

What is the best way to activate an <ion-datetime> with an <ion-button>?

Im currently attempting to execute the following action: I would like to select only the month and year using the example below: <ion-datetime presentation="month-year"></ion-datetime> However, I do not wish for this label to be vis ...

How can the service receive the return value from a subscribed subject?

I have a question about whether it is possible to retrieve the value from a call to Subject.next(). Can you suggest any other approaches on how to receive a response in the given scenario? My current situation involves a notify service that is used throug ...

Tips on effectively utilizing Chart.js with Typescript to avoid encountering any assignable errors

I'm encountering an issue while utilizing the Chart.js library in my Angular application with Typescript. The error message I'm receiving is as follows: Error: Object literal may only specify known properties, and 'stepSize' does not e ...

Error encountered during Jasmine unit testing for the ng-redux @select directive

Here is a snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { select } from 'ng2-redux'; import { Observable } from 'rxjs/Observable'; import { PersonalDetailsComponent } from ' ...

Utilizing Angular2 (Frontend) and Spring Boot (Backend) for Excel file uploading

As someone who is new to Angular 2, I am currently attempting to upload an Excel file from the Angular 2 frontend. My goal is to upload the Excel file from the Angular 2 frontend, send it to the Spring Boot backend for necessary modifications, and th ...

Is it possible to retrieve the precise key currently indexed within type declaration?

I am currently working on developing a simple type that would require a nested object key to reference the outer level. For better understanding, let's take an example: const obj = { foo: { name: 'bar', ref: 'foo' // & ...

No contains operator found in Material UI Datagrid

While working on a project, I utilized Material UI's datagrid and successfully implemented filters such as contains and isEmpty. However, I am struggling to find information on how to create a notContains filter. Does Material UI natively support this ...

Displaying a random element from the state array in React Native

I'm attempting to display a random item from the state array, with the possibility of it changing each time the page reloads. Here's what I have tried so far, any suggestions or ideas are welcome! This is my current state: state = { randomIt ...

The parent class has not been specified

I am facing an issue with my parent class, HTTPConnection, which I intend to use as a network utility class in order to avoid redundant code. However, when attempting to utilize it, the file core.umd.js throws an error stating Uncaught ReferenceError: HTTP ...

Angular 2 404 Error persists despite successful retrieval of data from Oracle database using Backend Nodejs URL entered directly into the browser

Recently, I've been working on displaying data in my Angular frontend that is fetched from an Oracle DB connected to my Node backend. When I access the physical API link, the data appears and is displayed in the backend console.log. I'm wonderin ...

What is the correct way to configure the environment variables for the vscode plugin?

After attempting to set it using cross-env, the variable remained undefined following execution in VSCode. What steps can I take to resolve this issue? https://i.sstatic.net/bKYLe.png ...

Securing Angular 2+: Safeguarding Server-Side Lazy Loaded Modules

In my Angular 2+ application, users input personal data that is then analyzed in a different section of the app restricted to authorized personnel. The challenge lies in preventing unauthorized individuals from gaining insight into the analysis process. We ...

Discover the new method for establishing fixed column widths in the PrimeNG table now that the Autolayout property is no longer in use

Previously, I was able to customize the width of th elements in the primeng table template by using style="width: 25%". However, it seems that this feature is no longer supported and the documentation now mentions that autolayout is deprecated, resulting ...

Error in unit testing: Trying to access property 'pipe' of an undefined variable results in a TypeError

Recently, I've been faced with the challenge of writing a unit test for one of the functions in my component. The specific function in question is called 'setup', which internally calls another function named 'additionalSetup'. In ...

Updating Angular 9 values using a fixed object

I am dealing with a patch value here where I simply pass an object to it. this.formPesquisar.controls['daniloTeste'].patchValue(this.dadosVisualizar.daniloTeste); However, I would like to pass a static object instead, something like: this.formPe ...