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

What causes the occurrence of `possibly null` errors within the if-condition?

We've implemented the strictNullInputTypes setting in our tsconfig.json. Within the component, there's a straightforward observable: export class ExampleComponent { obs$ = of({ prop: 12 }).pipe(delay(1000)); } In the component templa ...

How to focus on an input element in Angular 2/4

Is there a way to focus on an input element using the (click) event? I'm attempting to achieve this with the following code, but it seems like there may be something missing. (I am new to Angular) sTbState: string = 'invisible'; private ele ...

The art of transforming properties into boolean values (in-depth)

I need to convert all types to either boolean or object type CastDeep<T, K = boolean> = { [P in keyof T]: K extends K[] ? K[] : T[P] extends ReadonlyArray<K> ? ReadonlyArray<CastDeep<K>> : CastDeep<T[P]> ...

What is the purpose of the 'unique' keyword in TypeScript?

While coding in the TypeScript playground, I stumbled upon a situation where the term unique seems to be reserved. However, I haven't been able to find any official documentation regarding this. https://i.stack.imgur.com/eQq5b.png Does anyone know i ...

Unable to retrieve a method from the model class in Angular 4

I attempted to utilize a method from the model class, but encountered an error: ERROR TypeError: act.sayHi is not a function Below is my code snippet: Model Class myModelClass.ts export interface IMymodel { name: string; addres ...

The search with Mongoose find() results in an array with no elements

Currently, I am in search of a particular collection that I know exists within my mongoDB database. However, although I previously had success accessing it through my express server, it seems to be failing now. The connection to the database has been estab ...

Testing NextJS App Router API routes with Jest: A comprehensive guide

Looking to test a basic API route: File ./src/app/api/name import { NextResponse } from 'next/server'; export async function GET() { const name = process.env.NAME; return NextResponse.json({ name, }); } Attempting to test ...

Implementing dynamic display of div based on dropdown selection in typescript

A solution is needed to display or hide specific div elements based on a dropdown selection using Typescript. Sample HTML file: <select class="browser-default custom-select"> <option selected>single</option> <option value="1"> ...

React Query successfully retrieves the path, but unfortunately fails to render the image in the display

Currently facing an issue where I am trying to retrieve images from the backend using ReactQuery. Here is the ReactQuery code snippet: export const useGetProductImagesByProductId = (productId: string) => useQuery({ queryKey: ['productIm ...

What steps are involved in adding a table footer to ng2-smart-table?

I'm currently incorporating ng2-smart-table into my application. I am looking to include a table footer below the table to provide additional information such as Sum Amount, Discount Amount, and more. Below is an example of my code in a TypeScript fi ...

The desired resource does not accommodate the HTTP method 'OPTIONS'

When I attempt to send a request to an asp.net web api PUT method from my angular.js client using the following code: var org = { OrgId: 111, name: 'testing testing' }; $http.put("http://localhost:54 ...

Guidelines for incorporating Context API in Material UI

Currently, I am encountering a TypeScript error while attempting to pass a property using the Context API within my components. Specifically, the error message reads: "Property 'value' does not exist on type 'String'" To provide conte ...

PrismaClientValidationError: The `prisma.user.create()` method was called with incorrect parameters:

I am currently in the process of developing an API using Next.js and Prisma. Within this project, I have defined two models - one for users and another for profiles. My goal is to create a new user along with their profile by fetching data from req.body th ...

Oops! Looks like Laravel has hit its limit with 256 nesting levels in the function

I recently encountered a problem while working with an API that provides a mixture of JSON, STDClass, and Arrays. My main focus was extracting specific data from this nested structure which I managed to accomplish. However, the issue arose when I attempted ...

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

Why bother with importing { DOCUMENT } from '@angular/common'; when I can already easily access the document?

What is the advantage of using import { DOCUMENT } from '@angular/common'? Even if not used, I can still access the document module. document.getElementById('TestID).focus() The only variation I notice with the import is that it is linked ...

Enhance user information by adding necessary fields

I often encounter situations where I need to select a specific entry from a set of data in a component, whether through a select box or as part of a table. However, the way I intend to utilize this data typically requires additional fields like the "label ...

What is the best way to set up role redirection following a successful login within my MEAN stack application?

I have successfully developed a MEAN stack application with a functioning backend and frontend. However, I am looking to enhance it further by implementing role-based redirection after login. There are 5 roles in the system: admin, teacher, nurse, sportsma ...

Issue with assigning objects to an array

I'm currently working on a TypeScript application and I've run into an issue with assigning values. Here are the interfaces for reference: export interface SearchTexts { SearchText: SearchText[]; } export interface SearchText { Value: st ...

The TypeScript 'object' type

My query regarding the definition of TypeScript's {} type has brought about some confusion. Initially, I believed it represented an "empty object with no properties," but I recently encountered an ESLint rule that prohibits the use of {} type because ...