What is the best way to transfer data to the server in a loop without encountering synchronization issues?

I am working with an array of products in typescript (in angular) and my goal is to update their prices in the database using http calls.

The way I currently insert them is as follows:

array.foreach(element=>{
   this.product.price=element;
   this.myService.func(this.product).subscribe(a=>{console.log(a);});
})

However, the issue with this code is that the final data is incorrect due to server response times. This means that for the last two objects in the array, the same price as the last member of the array will be sent to the server.

To provide a clearer example:

Let's say the array has initial prices like this:

[0]=10
[1]=20
[2]=30

In addition to this array, I have a product instance:

Product p = new Product('product',50);

Now, my objective is to add 3 more products to the database with the name 'product' and the corresponding prices from the array, using a function from the server.

The desired outcome is all the products inserted into the database:

product,10
product,20
product,30

Unfortunately, I am getting a different result than expected:

product,10
product,30
product,30

Is there a way to fix this issue?

Thank you for your assistance.

Answer №1

  1. Instead of running requests sequentially, consider using the concat operator:
concat(array.map(element=>{
    this.item.price=element;
    return this.service.method(item)
})).subscribe(result=>{console.log(result);});
  1. Be mindful that updating the same product instance on each iteration may lead to unexpected behavior.

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

Despite the fact that one field is optional, failing to enter it will still result in the form being considered invalid

Although one of the fields is not mandatory, the form still shows as invalid when left empty. I have been attempting to resolve this issue without success. app.component.html <form [formGroup]="multiSelectForm"> <div formGrou ...

What is the best way to differentiate between the legend and chart when working with three separate

I have encountered an issue with my pie charts. The first chart has 10 legends displayed below it, while the second chart only has 4 legends. When I adjust the padding to accommodate the 10 legends in the first chart, the names of the 4 legends in the se ...

Issue encountered with Mongoose: Error 404 occurs while attempting to delete an object from a collection

I've encountered a strange issue with a mongoose API that is supposed to remove an object from a collection. When I call the API and pass the ID as a parameter (I have verified that the ID exists), I receive a 404 response. Here's how I am call ...

Switch up the Angular base URL using ngx-translate

I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu. Currently, the URL appears as: "localhost:4200". However, upon launching the project, it ...

Implementing asynchronous data sharing within an Angular 2 service

I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server. Here is an example of what my service code looks like: import {Injectable} from 'angular2/co ...

Compilation in AOT mode encountered an error due to an unexpected occurrence of the value 'null' in the AppModule file

Attempting to enable AOT compilation in Angular, I've encountered a specific error: 'Unexpected value 'null' declared by the module 'AppModule' In my project, I am utilizing PrimeNg modules, AGgrid, and ng2-adal. After adju ...

Ways to change a value into int8, int16, int32, uint8, uint16, or uint32

In TypeScript, the number variable is floating point by default. However, there are situations where it's necessary to restrict the variable to a specific size or type similar to other programming languages. For instance, types like int8, int16, int32 ...

Organize array by "categories" in Javascript and preserve the original sequence

There is a dataset presented below: [ { "name": "Item1", "section": "section1", "total": 3, }, { "name": "Item1", "section": "section2", "total": 4, }{ "name": "Item1", "section": "section3", "total": 7, }, { "name" ...

Ways to dynamically insert a new row into a table based on user input in a Postman-like reactive table

Is there a way to dynamically insert a row when a single character is entered into an input field in the header tab, similar to how Postman functions? 1) If a user types any single character in the td of the first row, then a new row should be added below ...

What are the limitations of jest and jsdom in supporting contenteditable features?

I am facing an issue with a particular test case: test('get html element content editable value', () => { // arrange const id = 'foo'; document.body.innerHTML = `<div id='${id}' contenteditable="true">1</div ...

React Native error - Numeric literals cannot be followed by identifiers directly

I encountered an issue while utilizing a data file for mapping over in a React Native component. The error message displayed is as follows: The error states: "No identifiers allowed directly after numeric literal." File processed with loaders: "../. ...

Ways to set a default selection for an md-radio-button in md-radio-groups

My button group consists of 3 radio buttons for filtering data, and I would like to have a specific button selected by default when the page loads. Below is the code snippet: <md-radio-group ng-model="status" aria-label="filter" ng-model="status" name ...

Issue with Primeng p-chips component: unable to dynamically add objects

Passing an array of objects value1 to the p-chips component is causing some issues. app.component.ts import { Component } from '@angular/core'; import {MenuItem} from 'primeng/api'; @Component({ selector: 'app-root', tem ...

Adjust the appearance attribute of FormField within the designated theme

Currently, I am collaborating within an NX Monorepo and utilizing a shared ui-components library that extends the capabilities of Angular Material Components. Despite using different themes for various applications, I am aiming to incorporate appearance=&a ...

The ASP.NET Core Web API is designed to handle incoming dates that are one day in the past, as sent by

After selecting a date from an Angular material datepicker, the ASP.NET Core Web API consistently receives the date as one day earlier. The date being sent is obtained from a form control and assigned to a property like so: scheme.date1 = this.formControl ...

Troubleshooting a problem with Angular2 involving the This.http.get function

Currently, I am delving into Angular 2 and have set up an ASP.NET WebApi locally hosted in IIS at http://localhost:8081/ping. The API call successfully returns a string serialized as a JSON Object. Below is the code for my service: import { Injectable } ...

Autocomplete feature in Angular not showing search results

I am currently using ng-prime's <p-autocomplete> to display values by searching in the back-end. Below is the HTML code I have implemented: <p-autoComplete [(ngModel)]="agent" [suggestions]="filteredAgents" name="agents" (completeMethod)="f ...

Is it possible to utilize the returned value of a function within an if statement?

Is there a way to return the result of a function without needing to declare a variable? Can you return the result of a function in a single line? How can you return the result of a function inside an if statement? Is it possible to use a function's ...

The declaration module in Typescript with and without a body

I am facing an issue with importing a .mdx file. When I include the following in my mdx.d.ts: /// <reference types="@mdx-js/loader" /> import { ComponentType } from "react"; declare module '*.mdx' { const Component: ...

An issue arose during the installation of the package 'npm i angularfire2'

I am currently working on an Angular project and I am trying to import AngularFireStorage using the following line of code: import { AngularFireStorage } from 'angularfire2/storage'; I attempted to do this by running the command npm i angularfire ...