Error: The function list.forEach does not exist within service.buildList [as project]

Today, I've been grappling with a challenging issue. As someone new to Typescript and Angular, I'm attempting to make a call to my backend API. However, when trying to populate an array for display, I keep encountering an error that says rawRegistrosList is undefined.

The error message I'm receiving is: "TypeError: rawRegistrosList.forEach is not a function at ConsultaService.buildConsultaList." Simply put, it's driving me slightly insane. And please excuse any mistakes in my English...

consulta.service.ts

private buildConsultaList(res: any){ // res has data when debugging
    this.registros = [];
    var rawRegistrosList: any[] = res.data; 
    rawRegistrosList.forEach(rawElement => { // error here, in rawRegistrosList.forEach
      var registro : Consulta = new Consulta();
      registro.cifEmpresa = rawElement.cifEmpresa;
      registro.nombreEmpresa = rawElement.nombreEmpresa;
      registro.ccc = rawElement.ccc;
      registro.afiliado = rawElement.afiliado;
      registro.nombreCompleto = rawElement.nombreCompleto;
      registro.identTrab = rawElement.identTrab;
      registro.altaMC = rawElement.altaMc;
      
      this.registros.push(registro);    
    });
    
    console.log("1 this.registro");
    console.log(this.registros);   
    return this.registros; 
  }

consulta.json:

{ "data": { "idTrabajador": 1, "cifEmpresa": "20855585", "nombreEmpresa": "Poleomenta SL", "ccc": "08/254891/22", "nombre": "Pepito", "nombreCompleto": null, "primerApellido": "Grillo", "segundoApellido": "Grillado", "identTrab": null, "afiliado": "Si", "altMC": "No", "razonSocial": "Razón Social 1", "nifEmpresa": "5697413J", "direccion": "Calle desengaño 21", "localidad": "Alicante", "cp": "032120", "ubg": "", "tipoIpf": null, "ipf": null }, "backendError": null, "httpResponse": true, "totalCount": 0 }

I'm looking for some guidance on what's causing this error and if I'm initializing everything correctly. Any insights would be greatly appreciated.

Answer №1

My assumption is that the content of consulta.json can be found within the variable res.

The object res.data does not include the key entity or a list, but rather just a single element.

To address this issue, consider the following approach:

let registrosList: any[] = [];
registrosList.push(res.data);

You can then proceed with your iteration using registrosList.forEach

Answer №2

When consulta.json is the returned data, it should be noted that it is not an array but rather an object! It is important to remember that objects cannot be iterated using JavaScript array methods.

The current output consists of:

{
    information: {...} // object
}

To iterate through this data effectively, you will need an array structure:

{
    information: [....] // array
}

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

Changes in tabs are discarded when switching between them within Material UI Tabs

I have been experiencing an issue with the Material UI tab component where changes made in tabs are discarded when switching between them. It seems that after switching, the tabs are rendered again from scratch. For example, let's say I have a textFie ...

Exploring the method of extracting data from a JSON response containing various objects

I am working with a REST API that returns multiple objects within a single JSON response. My goal is to extract specific data from all objects in the response using Python 2.7. How can I efficiently retrieve the "key", "name", and "emailAddress" for each ...

Operating CRUD operations in ASP.NET MVC utilizing Entity Framework, AngularJS, and Web API

I need to create a website using ASP.NET MVC with AngularJs, Entity Framework, and Web API. Can someone offer guidance on how to perform CRUD operations for this project? I am looking for assistance in executing CRUD operations... ...

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

Retrieving the final element from a TypeScript JSON array

I am trying to retrieve the value of the "id" property from the last element in an array of JSON objects. While I can easily find each element by id, I specifically need to extract the value of the last "id" in the array of JSON objects. In the example p ...

Updating the filter predicate of the MatTableDataSource should allow for refreshing the table content without needing to modify the filter

Currently, I am working on dynamically altering the filterPredicate within MatTableDataSource to enhance basic filtering functionalities. I want to include a fixed condition for text filtering (based on user input in a search field) for two string columns ...

Angular TypeScript test checking file size with Jasmine

Seeking optimal method for testing File size during input type="file" change event. Currently, my test specification appears as follows: it('attach file with too large size', () => { const file: File = { name: 'filename', ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

Mapping through multiple items in a loop using Javascript

Typescript also functions Consider an array structured like this const elementList = ['one', 'two', 'three', 'four', 'five'] Now, suppose I want to generate components that appear as follows <div&g ...

Error in NextJS with TypeScript when updating data in a useState variable

Recently, I started working with TypeScript, ReactJS, and NextJS, but I encountered a TypeScript error that I need help fixing. My current project involves using NextJS 14, server actions, and Prisma as the ORM for a university-related project. An issue ar ...

What is causing the failure of the state to be inherited by the child component in this scenario (TypeScript/React/SPFX)?

For this scenario, I have a Parent class component called Dibf and a Child class component named Header. While I can successfully pass props from the Parent to the child, I am encountering difficulties when trying to pass state down by implementing the fo ...

Is Angular 2 built on Shadow DOM or Virtual DOM architecture?

When it comes to updating the DOM in Angular 2, does it utilize Shadow DOM or Virtual DOM? And did Angular 1 have a similar concept? ...

Encountering a problem with the installation of angular-cli

When running ng serve on my Mac, I get the error -bash: ng: command not found. It seems like I need to install angular-cli. However, when I try sudo npm install -g angular-cli, I encounter the following issues. Does anyone have any idea what might be wron ...

Template URI parameters are being used in a router call

Utilizing the useRouter hook in my current project. Incorporating templated pages throughout the application. Implementing a useEffect hook that responds to changes in the router and makes an API call. Attempting to forward the entire URL to /api/${path ...

Release a new font on npm for integration into your project

In my current web-application project using angular2, I've designed a unique set of music glyphs such as notes, dotted notes, and time signatures. I couldn't find an existing font that suited my needs, so I created this custom font hierarchy: f ...

What is the best way to disable a submit button based on form validity in Angular 4 with ng-content?

Include a form component that consists of an email field, password field, and submit button passed through ng-content. This allows the login form to display a 'Login' button and the register form to display a 'Register' button. Here is ...

Working with TypeScript to set a value for an object's field

I have two objects of the same model: interface Project { _id?: string title: string description: string goal: string tasks?: Task[] createdAt?: Date updatedAt?: Date } The first object contains all fields from the interface, while the secon ...

The fuse box was to blame for triggering a GET request to http://localhost:4444/, resulting in the error message

I encountered an issue with fuse-box and P5.js where I received a GET http://localhost:4444/ net::ERR_CONNECTION_REFUSED. The complete code can be accessed on GitHub. The fuse.js file contains the following configuration: const { FuseBox, WebIndexPlugin ...

Angular error: Attempting to create a property on an empty string using Rxjs

Currently, I am working with Angular 11 and using rxjs. I am trying to filter my course collection to show only courses with the category "frontend," but I am encountering some errors. Here is my code: getPosts():Observable<ICourses[]> { return ...

What is the process for importing a component at a later time?

I am attempting to import components with a delay in a seamless manner. My goal is to import the components discreetly so that they load smoothly in the background while viewing the homepage. I experimented with lazy loading, but found that it caused dela ...