Angular not successfully passing ID in for loop

I am trying to pass the res[i].id value to my ArrayList while maintaining the sequence. Can anyone help me understand why 809 and 806 are not getting added to the arrayList correctly?

0: {id: 0, ArrayListID: 809, VarName: "TEST001A"}
1: {id: 0, ArrayListID: 806, VarName: "TEST002A"}
2: {id: 0, ArrayListID: 0, VarName: "TEST001B"}         //desired result
3: {id: 0, ArrayListID: 0, VarName: "TEST002B"}


809
809    // res[i].id goes here 
806
806


varName:any[] = [];

postTesting(){
  this.serv.postTest(this.fg.value?.dRay).subscribe((res:any[])=>{
    console.log(res)
    for(var i = 0; i < res.length; i++){
      this.varName[i].ArrayListID = res[i].id
    }

    this.serv.postTest1(this.varName).subscribe((r)=> {
      console.log()
    })
  })
}

Answer №1

It seems like there might be a misunderstanding in the question, as the assignment appears to be reversed.

for(var i = 0; i < this.res.length; i++){
  res[i].id = this.varName[i].ArrayListID
}

Instead, it should be:

for(var i = 0; i < this.res.length; i++){
  this.varName[i].ArrayListID = res[i].id
}

By making this change, you can update this.varName before calling serv.postTest1. Currently, data is being transferred from this.varName to temporary variable res, leaving this.varName unchanged.

Additionally, I recommend exploring strategies to avoid nested subscribes as mentioned by @churill yesterday:

Answer №2

Make sure to use res.length instead of this.res.length for response

for(let i = 0; i < res.length; i++){
   this.varName[i].ArrayListID = res[i].id
}

Answer №3

I'm a bit confused about the functionality of your code, especially regarding the output of the postTest methods.

Here is a potential solution:

    this.generateIds()
      .pipe(
        map((ids) => {
          var index = -1;
          return ids.map((id) => { 
            index += 1;
            return { ...testData[index], ArrayListId: id }});
        })
      )
      .subscribe((result) => console.log('result', JSON.stringify(result)));
  }

The generateIds() function should be equivalent to

this.serv.postTest(this.fg.value?.dRay)
, assuming it returns an array of IDs.

In the provided code snippet, the pipe operator processes the emitted array of IDs.

Using the map operator, each ID in the array is transformed into a new object with the corresponding ArrayListId.

Within the map function, ids.map iterates over each ID in the array and creates a new object with the original properties along with the additional ArrayListId property.

The resulting output would look like this:

[{"id":0,"VarName":"TEST001A","ArrayListId":809},
{"id":0,"VarName":"TEST002A","ArrayListId":809},
{"id":0,"VarName":"TEST001B","ArrayListId":806},
{"id":0,"VarName":"TEST002B","ArrayListId":806}]

Does this align with your intended functionality?

Additionally, it's recommended to avoid nested subscriptions for better code readability and maintenance. You can learn more about this concept in the following video: https://youtu.be/KiJ-e5QuWe4

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

Why does Angular throw a length-related error, while I am able to retrieve the length using console log if needed?

It appears that Angular is not receiving the correct data type it expects, yet the lack of errors in the terminal is puzzling. However, the console output states: https://i.stack.imgur.com/1xPsg.jpg If the length property can be detected (highlighted in ...

Encountering a Typescript Type error when attempting to include a new custom property 'tab' within the 'Typography' component in a Material UI theme

Currently, I am encountering a Typescript Type error when attempting to add a custom new property called 'tab' inside 'Typography' in my Material UI Theme. The error message states: Property 'tab' does not exist on type &apos ...

Service in Angular - Triggering a signal with an HTTP request

I have created a service with the following structure: const initialState: IUserState | null = null @Injectable({ providedIn: 'root' }) export class AuthService { private user = signal(initialState) constructor (private http: HttpClient) { ...

Unable to simulate axios instance in a Typescript environment

After reading through this particular article, I decided to attempt writing a unit test while simulating Axios (with Typescript). Incorporating an Axios instance to define the baseUrl. // src/infrastructure/axios-firebase.ts import axios from 'axios ...

Escape from the abyss of callback hell by leveraging the power of Angular, HttpClient, and

I'm currently grappling with understanding Angular (2+), the HttpClient, and Observables. I'm familiar with promises and async/await, and I'm trying to achieve a similar functionality in Angular. //(...) Here's some example code showca ...

Understanding the concept of mutable properties in Typescript

Why can the property 'name' in the class 'PersonImpl' be reassigned even though it is not declared as read-only in the Person interface? interface Person { readonly name: string; } interface Greeting extends Person { greet( ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

How to make sure that an element overflowing its container always starts from the top

My website has a section called <mat-drawer-container>, which contains a list of items called <mat-selection-list>. However, when the number of elements in the list exceeds the display height and scrolling is necessary, the scroll position star ...

Acquire the URL using Angular within a local environment

I am currently working on a basic Angular project where I have a JSON file containing some data. [{ "name": "Little Collins", "area": "Bronx", "city": "New York", "coverImage": "https://images.unsplash.com/photo-1576808597967-93bd9aaa6bae?ixlib=rb-1.2.1&a ...

Why isn't the constraint satisfied by this recursive map type in Typescript?

type CustomRecursiveMap< X extends Record<string, unknown>, Y extends Record<string, unknown> > = { [M in keyof X]: M extends keyof Y ? X[M] extends Record<string, unknown> ? Y[M] extends Record<st ...

I have encountered an issue while utilizing dynamic form functionality in Angular 7. The error message displayed is: "Error: Cannot find control with name: 'i'"

While working with Angular 7 dynamic forms, I encountered an error that I'm struggling to resolve. As a newcomer to Angular, this has been quite challenging for me. import { Component } from '@angular/core'; import {FormBuilder, FormArray} ...

"Encountering a 400 bad request error when making a Graphql POST

Seeking assistance with my graphql code. I have included the service and component files below. I am currently new to graphql and not utilizing the apollo client; instead, I am attaching a query on top of the HTTP POST call to send requests to the graphql ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

The argument type provided for returning an object in Rxjs switchmap is not valid

I have created a service in Angular that fetches data from different services and combines it with the initial service's data. If the initial service returns empty data, there is no need to call the second service. Here is the code: searchData(): Obs ...

Creating Typescript type definitions for any object properties

Struggling to find the correct TS syntax with Typescript 3.7.3. I have a random object, for example: var obj = { one: ..., two: ... three: ... }; I want to create a type that includes all keys from that object, like this: type ObjKeys = &ap ...

How is it possible that there is no type error when utilizing copy with spread syntax?

When I use the map function to make a copy of an array of objects, why doesn't it throw an error when adding a new property "xxx"? This new property "xxx" is not declared in the interface. interface A{ a:number; b:string; }; let originalArray:A[] ...

What is the correct way to specify an image path for a background URL?

Currently, I am setting a background image for the hr tag using the following code: <hr style="height:6px;background: url(http://ibrahimjabbari.com/english/images/hr-11.png) repeat-x 0 0;border: 0;margin:0px!important"> However, I have now saved th ...

Updating Angular 13 with charts.js and ng2-charts may expose unfixed vulnerabilities

I am facing an issue while updating chart.js and ng2-charts in Angular 13. After running npm i [email protected] and npm i [email protected], I encountered vulnerabilities that couldn't be resolved with npm audit fix. Do I need to update any ...