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

Different ESLint configurations for mjs, js, and ts files

For my project, I've set up ESM (.mjs) files for server-side code, CommonJS (.js) for tooling, and TypeScript (.ts) for the client side. In VS Code, when I look at CommonJS files, I'm getting errors related to requires such as "Require statement ...

Setting the base path for npm tests: A step-by-step guide

I am currently working on a web application that utilizes Angular as the front-end technology and Java Spring Boot as the backend. https://i.sstatic.net/IWPNZ.png In the screenshot above, you can see that I have created a new directory within the root fo ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Using Angular: filtering data streams from a date range observable object

I have a piece of code that seems to be functioning correctly, but I can't shake the feeling that it might just be working by chance due to an undocumented feature. I'm torn between questioning its validity or accepting that it is indeed designed ...

How to properly pass a parameter value to an Angular service when using inject.get in the constructor

After experimenting with injecting services in Angular, I encountered an issue when trying to call LogService within GlobalErrorHandler. Despite my best efforts, the code below just wouldn't work. I discovered that the problem stemmed from not passin ...

Is it possible for an Interface's property to be a type that contains an array?

As I dive into the Angular code, I encountered a peculiar type for a property within an Interface named 'Origin' that has left me perplexed. Here's the snippet: export interface Origin { areaNum?: number; open?: { [key: stri ...

Having trouble configuring Jest for TypeScript integration

I am currently implementing unit testing for a typescript project following the guidelines in this example: https://dev.to/muhajirdev/unit-testing-with-typescript-and-jest-2gln In my project, I have a file named main.ts that exports an isInternalLink func ...

Experiencing problems with React createContext in Typescript?

I've encountered a strange issue with React Context and Typescript that I can't seem to figure out. Check out the working example here In the provided example, everything seems to be working as intended with managing state using the useContext ...

What is the process for updating the Vue template during runtime?

Currently, I am working on a CMS-based Vue page. Within this page, there is a root container that contains two child containers structured as follows: <div id="app"> <div class="above-the-fold">...</div> <di ...

Unit testing subscription inside an Observable in Angular 4: A step-by-step guide

I'm currently testing a service that is being used in my Angular CLI project. I've managed to test all the functions except for those with a subscribe method, which is causing some issues. I would appreciate any guidance on how to properly test t ...

The error message "Property 'originalUrl' is not found in type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'" appeared

In my TypeScript project, I am utilizing a gulpfile to initiate the process. Within the gulpfile, I am using express where I encounter an issue while trying to access req.originalUrl, with req being the request object. An error is thrown stating Property ...

What exactly is the data type of setInterval in TypeScript?

If I want to define the type of a variable that will be used with setInterval in the following code snippet: this.autoSaveInterval = setInterval(function(){ if(this.car.id){ this.save(); } else{ this.create(); } ...

There are no markers or popups currently displayed on the map

Utilizing the ngx-leaflet plugin for leaflet, I have established the base layers and integrated a listener for the leafletMapReady event. Within my handler, I attempted to add both a marker and a customized popup. The handler code is displayed below: init ...

When the ngFor data reaches a count of four, it will be shown in a separate container div

I am struggling to find a way to display my ngFor data in a new container div once the length reaches four. It's easier to hard code the data into separate divs, but using ngFor results in the data being displayed in a single container div. In the co ...

unable to expand navbar in Angular 5 project with Bootstrap 4

I am encountering an issue with my navigation bar in a project that uses Angular5 and Bootstrap4. The navigation bar is supposed to expand when the screen size is small, as indicated by the navbar-expand-sm class in Bootstrap4. However, the navbar remains ...

Working with Angular 4: Utilizing HttpResponse in a Component

I am attempting to retrieve the response from my POST request using Angular 4. Below is the code I am using: app.component.html: `findAccordiSmall(pagination: Pagination) { this.accordiListTableLoading = true; debugger; this.ac ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

Guide to resolving the issue of error Type 'void[] | undefined' cannot be assigned to type 'ReactNode'

I am attempting to map the data Array but I am encountering an error: Type 'void[] | undefined' is not assignable to type 'ReactNode'. Can someone please assist me in identifying what I am doing wrong here? Below is the code snippet: i ...

Processing HTTP requests routed from Firebase Hosting to Cloud Functions

I'm currently working on integrating data patching with my Firestore database using http. My goal is to achieve this without relying on an external server, by utilizing Firebase Hosting and Functions. Firstly, I set up my Firebase project and importe ...

Setting up a Mean Stack on AWS Lightsail

I am currently experimenting with AWS Lightsail and struggling to grasp how to set it up properly. I have successfully created a Bitnami MEAN instance. On my local machine, I have Angular 6 running via CLI and a NODE API backend on two different ports: 42 ...