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

Guide to changing base 64 into a byte Array

Struggling to convert base64 to byte Array in Angular. Attempted solutions have not been successful. // Handling file upload handleUpload(event) { if (event.target.files[0]) { this.file = event.target.files[0].name; } const file = event.targ ...

Navigate to a blank page using Angular once the button has been clicked

Having a simple home page with just one button, I wanted the user to be redirected to another page upon clicking the button. However, my attempts to achieve this have not been successful. Here's the code snippet from my app.component.ts file: app.com ...

What is the best way to verify a modification on an observable within a service mock?

Currently, I am faced with the task of testing a backend service stub that returns an observable. The method in question is as follows: public postStatus(handle: string): Observable<StatusReturn>{ setTimeout(() => { this.result = { ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

Interceptor causing Angular HTTP Client to return null value

Here are two examples of the code output in the console. In order to return an observable for an interceptor, I converted a local storage promise into an observable using switchmap. However, I am still receiving null as the value. The function is wrapped i ...

ESLint is unable to locate the OnInit function within the "@angular/core" module

There seems to be an error: import { Component, OnInit, Input, ViewChild, ElementRef } from "@angular/core"; OnInit not found in '@angular/core'eslintimport/named The code appears to be functioning correctly, so perhaps there is a m ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Error message: Angular 2 JsonpModule import not defined

Within my app.module.ts file, I have the specified code import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {JsonpModule} from '@angular/http'; import {AppComponent} from & ...

What is the proper way to create an array of dynamically nested objects in TypeScript?

Consider the structure of an array : [ branch_a: { holidays: [] }, branch_b: { holidays: [] }, ] In this structure, branch_a, branch_b, and ... represent dynamic keys. How can this be properly declared in typescript? Here is an attempt: ty ...

What is the relationship between directives, templates, and ViewContainers in Angular?

I have implemented a basic functionality in my component where numbers are injected after a delay using a custom directive called *appDelay It is known that the Angular syntax hints with * will de-sugar into something like this: <ng-template ...> .. ...

Concealing Dropdown Box Information Based on a Customized List in Angular

Is there a way to remove an item from a dropdown list once it has been selected? For example, if I have a dropdown box with options 'Dog', 'Lion', and 'Cat', how can I make it so that once I select 'Dog', it will no ...

Transporting a Typescript file to the customer using JavaScript

As a newcomer to typescript and in the process of creating a small application in visual studio 2013, I have noticed that when viewing the project in Chrome's developer tools, typescript files (*.ts) are being downloaded to the client. This could pote ...

Angular toolbar on the left side that hovers seamlessly

1 I am using Angular Material toolbar and trying to position a span inside the toolbar on the left side. I have attempted using CSS float left, but it is not working. Can anyone provide some assistance please? <mat-toolbar> <span>le ...

How can I assign a type to an array object by utilizing both the 'Pick' and '&' keywords simultaneously in TypeScript?

As a beginner in TypeScript, I am looking to declare a type for an array object similar to the example below. const temp = [{ id: 0, // number follower_id: 0, // number followee_id: 0, // number created_at: '', // string delete_at: &ap ...

Is the regex returning the correct result?

I need to discuss the date field with a format of YYYYMMDD, as shown below: zod.string().max(8).regex(new RegExp('^(19[0-9][0-9]|20[0-9][0-9]|[0-1][0-9]{3})(1[0-2]|0[1-9])(3[01]|[0-2][1-9]|[12]0)$')); The value provided is 20001915. The definit ...

Angular 2 and beyond: delivering a unified global service instance for sub-modules

Exploring how to create a comprehensive service that can be accessed from submodules within an angular 2+ application is key. While the traditional component hierarchy setup works well for this, understanding the process when dealing with multiple modules ...

Improving type checking by extracting constant string values from a union type

I am exploring different types of employees: interface Employee { employeeType: string } interface Manager extends Employee { employeeType: 'MANAGER' // .. etc } interface Developer extends Employee { employeeType: 'DEVELOPER&apos ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

Error: "Reflect.getMetadata function not found" encountered during execution of Jenkins job

My Jenkins job is responsible for running tests and building an image. However, I am encountering issues with the unit tests within the job. task runTests(type: NpmTask) { dependsOn(tasks['lintTS']) args = ['run', 'test&ap ...

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...