When invoking a service repeatedly in Angular within a loop, the result is returned on the second iteration rather than the first

I've run into an issue where I'm attempting to invoke a service in Angular within a for loop and store the result in a Map.

map = new Map<string, string[]>();

this.effectivitiesList = this.trimEffectivities.split(",");

for (let effec of this.effectivitiesList) {
  this.hexcodeService
    .GetHexCodeLineValues(
      this.majorModel,
      this.wireNumber,
      this.selected,
      this.trimEffectivities,
      effec
    )
    .subscribe(data => {
      this.hexcodeLineList = data;
    });

  this.map.set(effec, this.hexcodeLineList);
}

console.log(this.map);

The issue arises because the data isn't retrieved successfully the first time the code is executed. The Map displays:

Map - >

VA305 , Array[0]
VA504 , Array[0]

However, on the second invocation of the method, the data is fetched correctly:

VA305 , Array[3]
VA504 , Array[3]

Any insights on why this might be happening?

Answer №1

To transform the surrounding function into an asynchronous one, utilize the async keyword. This will allow you to use await on the output of the hexcodeService. Additionally, substitute suscribe with toPromise to enable this transformation:

async myFunction() {
    for (let effec of this.effectivitiesList) {
        const data = await this.hexcodeService
            .GetHexCodeLineValues(
                this.majorModel,
                this.wireNumber,
                this.selected,
                this.trimEffectivities,
                effec
            ).toPromise();

        this.hexcodeLineList = data;

        this.map.set(effec, this.hexcodeLineList);
    }
}

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

Using ngFor to destructure two variables simultaneously

When working with Python, I found a way to unpack both variables in each tuple at every iteration. l = [(1, 2), (4, 5), (8, 9)] for k,v in l: print("k = ", k) print("v = ", v) print("-------") # k = 1 # v ...

Why hasn't the styles folder been generated in Nuxt 3?

After running the command "npx nuxi generate," the css folder does not seem to be created in the static site. What could be the issue? package.json: { "private": true, "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": ...

Determine in Typescript if a value is a string or not

In my code, I have a component: export type InputData = string | number | null; interface InputData { data?: string | number | null; validate: boolean; } const App: React.FC<InputData> = ({ data = '', validate = true, }) => ...

Updating elements within an array on the fly

In this scenario, let's consider two arrays: array A = [2, 5, 6] and array B = [1, 2, 3, 4, 5, 6, 7, 8]. The values of array B are initially hidden within boxes and become revealed when clicked. The goal is to replace certain values in array B with un ...

Locating the initial array within a set of nested arrays

One of the functions I'm working on has the ability to generate a nested array, especially for multiPolygon purposes. Here's an example of how it might look: [ [ [ 10.0, 59.0], [ 10.0, 59.0], [ 10.0, 59.0] ], [ [ 10.0, 59.0 ...

Attempting to use jQuery AJAX to submit data without navigating away from the current webpage

Trying to implement the solution provided in this post where I am trying to send data to a PHP page and trigger an action, but unfortunately, it seems to just refresh the page without any visible outcome. Even after checking the network tab in the element ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

Creating a sticky menu in a column using affix with a CSS bootstrap list-group

My goal is to develop a sticky menu utilizing CSS Bootstrap affix and the list-group menu. I have successfully implemented most of it, except for one issue when the user scrolls down. Upon scrolling down, the menu expands to fill the entire width of the ...

The GET request on the Express route is malfunctioning, causing the Postman request to time out after getting stuck for some

My Express app seems to be experiencing some issues with the GET route. When making a request using Postman, the response gets stuck for a while before fetching. The GET route is properly set up with all necessary request parsers and the app initialized an ...

An abundant array of options spread across numerous dropdown menus

I have been tasked by a client to do something new that I haven't done before, so I am seeking the best approach. The project involves creating a form with three dropdown menus where users can select from thousands of options. For instance: Users mu ...

ToggleButton4 Framework is a user-friendly tool for creating interactive

I am currently working with Bootstrap 4 to design a toggle button; however, when I click the button, the checkbox does not update, despite the fact that the active class is being applied. Even when I use $('.btn-group-toggle').button('toggl ...

Text area featuring unique border design, with border color change upon focus?

Currently, I have a text area with borders that are designed in a unique way. However, I am looking to change the border color when the user focuses on the text area. Do you have any suggestions on how I can achieve this effect without affecting the curre ...

Angular 7 is throwing an error message that reads: "Module not found: 'AppModule'"

When running ng build, an error occurs without providing any specific details like the file name. This project is an ASP.NET Core app with Angular 7. c:\Users\siva\Myapp\ClientApp>ng build Date: 2019-08-08T13:22:52.205Z Hash: 3cf960 ...

Unable to modify the hover color on the image or icon

After creating a circle icon with an image in the center, I wanted to make the image change colors on hover. The main focus of the icon is the circle itself. In my attempt to achieve this effect, I included the following code for the circle icon: .circle- ...

Execute asynchronous code in a Next.js component without relying on the UseEffect hook

Within my nextjs application, there is a StrapiImage component that takes in an image object from the strapi backend api as a prop. This component sets the width, height, URL, and any additional props for the image. Essentially, it serves as a shortcut for ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

What is the best way to create an interface that only allows keys to be a combination of values from a specific property found within each object of an array?

interface Filter { id: string; name: string; } type Filters = Filter[]; const filters = [{ id: 'f1', name: 'f1name'}, { id: 'f2', name: 'f2name'}] interface State { ... } const state = { f1: any, ...

Empowering Components with React Hooks

I am currently in the process of transitioning from using class components to React hooks with the Context API. However, I am encountering an error and struggling to pinpoint the exact reason for it. Here are my Codes: // contexts/sample.jsx import React ...

What can cause an "Undefined index" error in an ajax POST request and/or PHP script?

When attempting to send an ajax POST request to a PHP file, I encounter an issue where the PHP file returns a notice of "undefined index" and does not receive the value being sent. Despite researching extensively to find a solution, I have been unable to r ...

The Router.use() function is looking for a middleware function, but instead received an undefined value at the

Currently, I am working on implementing authentication with node.js following a tutorial. However, I have encountered some issues that I am struggling to resolve. This is how I have configured the server: // Inserted code for configuring the server The ...