Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows:

itemDefaultConfiguration.command = (onclick) => {
   this.createConfiguration(configuration.components);
   //wait for createConfiguration method to finish, which includes an http call with subscribe
   this.initializeAllComponents(configuration.components)
};

initializeAllComponents(components: Agent[]) {
    components.forEach(agent => {
      this.componentService.setAgent(agent);
      this.componentService.clearAnyOneOfIndex();
      // wait for setAgent method to finish, which includes an http call with subscribe
    })
}

Inside componentService:

setAgent(agent: Agent) {
        this.agent = agent;
        this.selectComponent(agent.name, undefined, "/", "/", environment.maxLevelJsonSchema);
    }

The selectComponent method also includes a subscribe:

selectComponent(agentName: string, propName: string, schemaPath: string, dataPath: string, deepLevel: number) {
        this.getComponentSchema(this.agentName, schemaPath, deepLevel)
            .subscribe((responseSchema) => {
                this.getDataFailure(propName, dataPath, responseSchema); 
            });
}

Can someone provide assistance? Thank you!

Answer №1

To accomplish this task, you can utilize the await function in your code as shown below:

initializeAllComponents(components: Agent[]) {
    components.forEach(async agent => {
      await this.componentService.setAgent(agent).catch(console.log);
      this.componentService.clearAnyOneOfIndex();
      // Ensure the setAgent method with a subscribe call inside is completed
    })
}

Answer №2

To accomplish this task, you can utilize the async/await syntax in JavaScript:

initializeAllItems(items: Product[]) {
    for (let i = 0; i < items.length; i++) {
        const product = items[i];
        await this.productService.setProduct(product).catch(console.log);
        this.productService.clearAnyOneOfIndex();
    }
}

It is important to note that when using async/await, it is essential to use a native for loop instead of methods like forEach or reduce since they do not wait for previous asynchronous calls to complete.

Answer №3

If you have an object that is Observable, consider implementing the switchMap operator:

import { switchMap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

initializeAllComponents(components: Agent[]) {
    components.forEach(agent => {
      this.componentService.setAgent(agent).pipe(
           switchMap(res => {
               if (res) { return this.userService.get(user.uid); }

               return of(null);
           }));
      );
      this.componentService.clearAnyOneOfIndex();          
    })
}

If your object is not Observable, then you can utilize the async/await operators instead:

async initializeAllComponents(components: Agent[]) {
    components.forEach(agent => {
      let result = await this.componentService.setAgent(agent);
      this.componentService.clearAnyOneOfIndex();
      // wait for setAgent method completion which includes a subscribe(http call) inside
    })
}

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

Managing state in a live chat application

Currently seeking advice on managing state in a real-time messaging/chat app created with VueJS 2. The application is made up of multiple components as shown in the diagram below: Up to this point, I have successfully implemented the display of (fake) co ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Empty area beneath the body in Chrome Device Mode

Can anyone explain why there is a strange blank space under the body tag in mobile view on Chrome (other browsers like Firefox and Internet Explorer display it correctly)? Here is the simple code that I am using: <html> <meta name="viewport" con ...

When attempting to utilize yarn link, I receive an error message indicating that the other folder is not recognized as a module

After successfully running "yarn link," I encountered an issue when attempting to use it in a different project. The error message displayed was ../../.tsx is not a module. What could be causing this problem? const App: React.FC = () => { const [op ...

When making a Get Request from Angular, the header fails to appear for servicing

I am currently working on an angular JS application where I need to call a GET API that is OAuth 2.0 enabled, requiring a Bearer Token in the header for authentication. The method I am using to make the HTTP request is as follows: var config = { heade ...

Leverage images within the Angular library

I am currently working on creating an Angular library that includes a component with an image. I have successfully added the image as an asset in the library, but when trying to display it, the image doesn't show up. Here is the current folder structu ...

Are there any notifications triggered when a draggable element is taken out of a droppable zone?

Within a single droppable area, there is a collection of individual Field Names that can be dragged, and a table featuring X headers, each of which can be dropped into. Initially, these headers are empty. Is there a way to detect when an item is taken out ...

Receive information from a form and store it in an array

Struggling to figure out how to convert this into an array. I'm having trouble grasping the concept of taking input from a form and storing it in an array. In my project instructions, it clearly states: Do NOT save the input in variables and then tra ...

Trouble with importing React JSX from a separate file when working with Typescript

This problem bears some resemblance to How to import React JSX correctly from a separate file in Typescript 1.6. Everything seems to be working smoothly when all the code is contained within a single file. However, as soon as I move the component to anoth ...

HTML Menu with Ajax functionality designed to work seamlessly without relying on JavaScript

I'm working on making my navigation system compatible with both clients who have JavaScript disabled and those who can use Ajax. Currently, I have dynamic links generated inside the navigation like "index.php?page=/cat/page.php". <li id="sidebarit ...

Unable to attach an event listener to an element fetched from an API

I'm currently in the process of developing a trivia web application using an API, and my goal is to incorporate an event listener onto the button which corresponds to the correct answer. This way, when users click on it, a message will appear confirmi ...

Is it impossible to modify an enumerable attribute within a JSON.stringify replacer function?

I'm having some trouble trying to serialize non-enumerable properties within the replacer function. Can someone point out what might be going wrong in this code snippet? Any help would be greatly appreciated. var obj = {x:1,y:2}; Object.definePrope ...

Setting up a chat feature in a Laravel application: A step-by-step guide

Looking to Enhance My Web-Application I have been working on a web-application that utilizes: Laravel for the back-end Angular for the front-end. Milestone Achieved! I successfully implemented the entire user authentication process including: User Aut ...

Troubleshooting IE Freezing Issue Due to JavaScript Code with .addClass and .removeClass

Need some help troubleshooting why my code is causing IE to crash. After commenting out sections, I discovered that the issue arises when using .addClass and/or .removeClass inside the if conditions: if ( percentExpenses > 50 && percentExpenses ...

Unable to access nested JSON in Angular 2

To sum up, if I use the following code: {{ foo.bar | json }} Assuming foo is a JSON object and bar is a JSON object within foo, Angular 2 will load the data in foo.bar correctly and display the JSON object. However, trying to access foo.bar.baz will resu ...

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...

Best practice for resetting jquery datatables for proper functioning

A user on Stack Overflow was seeking a solution for working with DataTables.js and a variable number of columns. The provided solution can be found here: http://jsfiddle.net/gss4a17t/. It's worth noting that this solution relies on a deprecated funct ...

HTML - one div's child element takes precedence over another div

My HTML page features two consecutive divs. The first div contains a child span that has a relative position, causing it to overlap the second div. I have implemented click events for both divs. However, when I click on the span that overlaps the second d ...

Leverage and implement personalized variables within an Angular toolbox

I have created an Angular library that includes a component called myComponent. The library builds successfully and can be used in my main application. I'm looking to enhance the functionality by allowing the main application to customize certain scss ...

Angular2 application encounters issue with target attribute being overlooked by Chrome

I am trying to implement a link in an iframe following the instructions on W3Schools: <iframe height="300px" width="100%" src="demo_iframe.htm" name="iframe_a"> </iframe> <p><a href="http://www.w3schools.com" target="iframe_a">W3S ...