What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this:

this.webService.add(id)
  .subscribe(result => {
    // perform required actions
  }, error => {
    // handle errors
  });

// Service Definition
add(id: number): Observable < any > {
  return this.http.post(this.baseUrl + 'webservice/add/' + id, null);
}

If you need to make multiple calls but ensure that all have completed before displaying a final success or failure message, how can you achieve that?

Would using a recursive method work, or is there a more suitable angular/javascript/callback approach?

For example:

for (let i = 0; i < someLength; i++) {
  this.webService.add(id)
    .subscribe(result => {
      // perform required actions
    }, error => {
      // handle errors
    });
}
// Now display if they all succeeded or if one failed!

The controller appears asynchronous in the following manner:

[HttpPost("document/{id}")]
public async Task<IActionResult> Document(int id) {
   // do something
   var resultDto = await _webRepo.AddToWebService(info);
   return Ok(resultDto);
}

Answer №1

If you are in need of the forkJoin operator, look no further.

By taking multiple observables and combining them into a new observable once all the source observables have completed, this operator proves to be quite handy. Here's how you can use it:

const asyncTasks = yourList.map(id => this.asyncService.execute(id));
forkJoin(... asyncTasks)
 .subscribe((results) => results.forEach( //manipulate results as needed ))

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 is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...

Is there a way to postpone the action so that the bot will not acknowledge the second command until after I have completed the first command

client.on('message', async (message) => { let author = message.author.username if (message.author.bot) return; if (message.content.startsWith('-queue open ')) { message.content = message.content.replace('-queue o ...

How can we leverage Shared and Core modules alongside Feature modules in Angular development?

When developing my Angular application, I have adopted a specific architecture approach and included a shared.module.ts file in the shared folder. While leveraging lazy-loading in my app, I find myself puzzled about the necessary imports, declarations, and ...

Activate the next tab by clicking a button in ReactJS

I currently have a web page with 4 tabs, each containing different sets of data. Within the first tab, I have a button that should activate the next tab's content when clicked by the user. render(){ return ( <MuiThemeProvider> ...

The xslt code is failing to invoke the JavaScript function

I am currently utilizing xslt for the transformation of xml to html. Below is an example of an .xml file. <ImportOrganizationUtility-logging> <log-session module-name="ImportOrganizationUtility" end="17:54:06" start="17 ...

Make sure the auto import feature in TypeScript Visual Studio Code Editor is set to always use the ".js" extension

At times, the auto-import completion feature includes the .js extension, but inconsistently. When this extension is missing in the TypeScript source, the emitted JavaScript file may encounter runtime issues like module not found error since the tsc compile ...

The functionality of my JQuery validation plugin seems off when it comes to handling checkbox inputs

I created a versatile validation plugin that accepts a function to check input validity, along with callbacks for valid and invalid cases. The plugin consists of two functions: '$.fn.validation()' to attach validation logic and success/failure ca ...

Angular 6's Select feature is failing to properly update user information

We are currently facing an issue with our user profile edit form. When users try to update their information by changing simple input fields, the changes are reflected successfully. However, when they make selections in dropdown menus, the values do not ge ...

Getting started with accessing an API using Angular 2

I am seeking a way to navigate outside of my Angular 2 application to mywebsite.com/api. This link should direct me to an API application hosted on the same server. Here is my current route configuration. export const routes: Routes = [ {path: '& ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

Ways to Conceal <div> Tag

I need help with a prank .html page I'm creating for a friend. The idea is that when the user clicks a button, a surprise phrase pops up. I have managed to hide and unhide the phrase successfully using JavaScript. However, my issue is that when the pa ...

What is the best way to display the nested information from products.productId?

How do I display the title and img of each product under the product.productId and show it in a table? I attempted to store the recent transaction in another state and map it, but it only displayed the most recent one. How can I save the projected informa ...

Narrow down an array of objects by matching a specific property and value to a separate array of objects

I am facing a challenge with two sets of arrays - one for the headers (columns) of a table and the other for the rows. const headers = [ { text: 'Dessert (100g serving)', align: 'left', sortable: false, value: 'n ...

"Error encountered: 'require' is not defined in the bundled JS file for

Recently, I decided to try my hand at Django and ReactJS. While attempting to compile a simple JSX code to JS, I followed this tutorial: . However, I encountered an error that prevented it from working. I then resorted to using npm run dev to compile the c ...

Improved method for categorizing items within an Array

Currently working on developing a CRUD API for a post-processing tool that deals with data structured like: { _date: '3/19/2021', monitor: 'metric1', project: 'bluejays', id1: 'test-pmon-2', voltageConditio ...

Encountering TS 2732 error while attempting to incorporate JSON into Typescript

Having trouble importing a JSON file into my TypeScript program, I keep getting error TS2732: Can't find module. The JSON file I'm trying to import is located in the src folder alongside the main.ts file. Here's my code: import logs = requi ...

Top Recommendations: Comparing Standalone Components and Modules in Angular Version 14

I'm in need of some clarification on the most effective practices when it comes to utilizing standalone components and modules within Angular 14. With the introduction of standalone components as a new concept in Angular, I am seeking factual guidance ...

Error Alert: missing property data in angular 5 type

I attempted to design an interface in interface.ts. The data consists of an array of objects inside the Column. Below is the code for my interface: export class User { result: boolean; messages: string; Column=[]; data=[]; } export class Column { name ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Having trouble getting a response when using formidable in Next.js?

I am working on uploading a file from the front end to my GCP workflow, and everything seems to be functioning correctly. However, I am consistently encountering an issue where the API resolved without sending a response message appears. I attempted to r ...