Manipulating objects from an HTTP Observable while iterating through an Array of objects

I am currently working on processing each element of an array by making a separate HTTP call for each element. I need to track the status of each call and update the UI once all calls are completed. The code snippet below demonstrates my current approach:

for (var singleData of this.someData) {
        this._Service.call(singleData.someData).subscribe(
            data=> {
                this.successGroups.push(singleData);
                this.checkState();
            },
            error=> {
                this.failureGroups.push(singleData);
                this.checkState();
            }
        )
    }

The service, this._Service, is a basic Angular2 HTTP service that returns observables from the calls. The goals for this process are:

  1. Make individual calls for each item in the list
  2. Mark successes as success and failures as failure
  3. Update the UI once all calls finish, regardless of their success or failure

The issue with the current code is that due to the asynchronous nature of the calls, the "singleData" variable gets updated before the subscriber functions execute. This leads to incorrect values being pushed into the success or failure groups.

Answer №1

Close, but I recommend a slightly different strategy - something in the realm of:

// Using Observable.from() to process array-like data and emit for each element
let requests$ = Observable.from(this.someData)
                          .flatMap(singleData => this._Service.call(singleData.someData);

requests$.subscribe(
   data => {
     this.successGroups.push(singleData);
     this.checkState();
   }, 
   error => {
     this.failureGroups.push(singleData);
     this.checkState();
   }
);

My approach is focused on minimizing the number of Observables and subscriptions. In your current method, you're creating n of each (where n is the length of your someData array), whereas with this approach, you only create 1 of each.

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

Tips for transferring data when clicking in Angular 5 from the parent component to the child component

I need assistance with passing data from a parent component to a child component in Angular 5. I want the child component to render as a separate page instead of within the parent's template. For example, let's say my child component is called & ...

String values not being set as default in Angular Material's mat-button-toggle-group

<div class="navigation"> <mat-button-toggle-group class="button-toggle" [(ngModel)]="langSelected" (change)="onToggleGroupChange($event)" [value]="langSelected"> <mat-button-toggle value=& ...

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

Broaden the scope of the generic interface utilized within the package

Wanting to incorporate automatic behaviors in RTK Query, I decided to implement debounced mutations and handle optimistic updates before the actual mutation request is made. The implementation has been successful so far. However, I am now focusing on gett ...

What is the advantage of utilizing the ng-idle library for monitoring user idle status when we have the ability to create custom JavaScript code to track inactivity based on keyboard and mouse events?

I have implemented a method to detect user idle time using mouse and key events as shown below. @HostListener('window:keydown', ['$event']) @HostListener('window:mousedown', ['$event']) @HostListener('window:mou ...

Leveraging the `--max-http-header-size` flag with ts-node

Encountered an issue when trying to use ts-node with the --max-http-header-size 15000 flag. It works fine with regular node, but unfortunately, ts-node does not support that option ...

Tips for enabling autofocus in mat-select列表。

I am working on an angular project where I am using Angular Material and a mat-select element. In my form, the mat-select is the first element, and I want to set auto-focus on it when the page loads. However, I have been facing some difficulties achieving ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Sending Component Properties to Objects in Vue using TypeScript

Trying to assign props value as an index in a Vue component object, here is my code snippet: export default defineComponent({ props:{ pollId:{type: String} }, data(){ return{ poll: polls[this.pollId] } } }) Encountering errors wh ...

Angular problem: Cannot connect to 'formGroup' as it is not a recognized property of 'form'

Struggling to set up a simple form in Angular consisting of a label and an input field. Despite following suggestions to import FormsModule and ReactiveFormsModule, I'm still encountering errors as mentioned numerous times on StackOverflow. Here&apos ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Create dynamic breadcrumb trails using router paths

I am currently working on developing a streamlined breadcrumbs path for my application. My goal is to achieve this with the least amount of code possible. To accomplish this, I have implemented a method of listening to router events and extracting data fr ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

Having trouble with showing dynamic data in column2 of my HTML layout, and the alignment doesn't look quite right in HTML

I'm working with this HTML file, attempting to create a two-column layout using HTML and CSS. I want one column to be labeled REQUEST and the other RESPONSE. When a value is entered in the text field in Column 1, it should display a response in Column ...

`ionic CapacitorJS extension for Apache server`

Currently, we are developing a hybrid mobile app using Ionic Capacitors. In the initial stages, we started with an Ionic Cordova project and then upgraded it to an Ionic Capacitor project using the latest version. For network requests, we utilized the fol ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

Unable to retrieve the third attribute of a Class using Angular2's toString method

Here is the code snippet I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <p><strong>Email:</strong> {{email}}< ...

SonarLint versus SonarTS: A Comparison of Code Quality Tools

I'm feeling pretty lost when it comes to understanding the difference between SonarLint and SonarTS. I've been using SonarLint in Visual Studio, but now my client wants me to switch to the SonarTS plugin. SonarLint is for analyzing overall pr ...

What is the best way for me to generate a fresh object?

In one of my components, I have implemented a feature where clicking on an image toggles a boolean variable to show or hide a menu. The HTML structure for this functionality is as follows: <img src="../../assets/image/dropdown.png" class="dropdown-imag ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...