Unable to loop through the "dataList" retrieved from a service call to the java backend within an Angular 9 application

After receiving JSON data from a Java backend service called houseguidelines, the information is sent to an Angular application via a service call. I am attempting to iterate over this returned JSON data and add it to an array I have created. Unfortunately, I keep encountering "undefined" errors in the browser console when trying to accomplish this task.

The service call within the Angular application is structured as follows:

export class HouseGuidelinesService {
   private readonly houseGuidelinesURL = 'http://localhost8200/homeguidelines';

   constructor(private http: HttpClient) {}

   getHouseData(houseCode: string): Observable<HouseGuidelineResponse[]> {
   
   return this.http.get<HouseGuidelineResponse[]>(this.houseGuidelinesURL + '/', {headers: {houseCodeList: houseCode}});    
}
}

The file responsible for sending data to the service call in the Angular application appears similar to this:

export class HouseComponent implements OnInIt {

houseData: HouseGuidelineResponse[];
houseList = [];

constructor(private activatedRoute: ActivatedRoute, private router: Router, private houseSummaryService: HouseService, private houseGuidelinesService: HouseGuidelinesService ) {}

callHouseService(houseCodeList) {
  this.houseGuidelinesService.getHouseData(houseCodeList).subscribe(
  (data) => {
  this.houseData = data;
  console.log('display house guidelines', this.houseData);
  console.log('first house data: ', this.houseData[0])
  },
  (error) => {
  console.log('Error Getting House Policy Info!');
  }
  );


}
}

The structure of the HouseGuidelineResponse object within the Angular application can be represented like this:

export class HouseGuidelineResponse {
id: number;
name: string;
description: string;
settings: HouseSettings[];
}

Although the service call successfully returns JSON data shown in the browser console like below:

dataList: Array(3)
  0: {id:1, name: 'house risk 1', description: 'the best guidelines', settings: Array(1)}
  1: {id:2, name: 'house risk 2', description: 'the next best guidelines', settings: Array(1)}
  2: {id:3, name: 'house risk 3', description: 'the worst guidelines', settings: Array(1)}

Issues arise when trying to iterate over or access elements within the dataList. For example, in the function callHouseService(houseCodeList), the following code snippet causes an error:

for (const value of this.houseData) {
 this.houseList.push({
 id: value.id
})
}

console.log(this.houseList)

An error message stating "houseData is not iterable" is displayed.

Similarly, attempts to access individual elements within the dataList result in being told that they are undefined. For instance, the code snippets below generate "undefined" errors in the browser console:

console.log('first element: ', this.houseData[0]);
console.log('maybe the first element: ', this.houseData[0].description);

Hence, my question is: how can I effectively iterate over the received JSON dataList to utilize its content and subsequently attribute it to my predefined object?

Answer №1

After executing the

console.log('display house guidelines', this.houseData);
code provided in the question, I have analyzed the response data as follows:

{
  "dataList": [
    {
      "id": 1,
      "name": "house risk 17",
      "description": "the best guidelines",
      "settings": [...]
    },
    {
      "id": 2,
      "name": "house risk 2",
      "description": "the next best guidelines",
      "settings": [...]
    },
    {
      "id": 3,
      "name": "house risk 3",
      "description": "the worst guidelines",
      "settings": [...]
    }
  ]
}

Considering that your getHouseData function returns a value of type

Observable<HouseGuidelineResponse[]>
, you can enhance it by adding the .pipe() method with the map operator from rxjs to extract and return response.dataList within the Observable.

.service.ts

getHouseData(houseCode: string): Observable<HouseGuidelineResponse[]> {
   return this.http
     .get<HouseGuidelineResponse[]>(this.houseGuidelinesURL + '/', {
       headers: { houseCodeList: houseCode },
     })
     .pipe(map((response: any) => response.dataList));
}

Check out a Sample Demo on StackBlitz

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

Storing numerous string labels and arrays in a TypeScript associative array

I am currently developing a mobile app using Ionic 4 where I need to store various labels and arrays in an associative array. However, I am encountering challenges when it comes to initializing the array, adding new items to it, and updating existing ones ...

Using AngularJS to send a $http.post request with Paypal integration

This form utilizes the standard PayPal format for making purchases. <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="<a href= ...

When invoking a function, jQuery may return an empty value

I am currently tweaking my jQuery script to retrieve a specific value upon page refresh in order to capture the return value. Initially, I attempted the following: var email_number = ''; // check if page refreshed or reloaded if (performance.n ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

What is the best approach for organizing JavaScript/CoffeeScript in a Rails 5 project for optimal efficiency?

I am currently working on a web application with Rails 5.0.2 and I have a set of JS files for the project: https://i.stack.imgur.com/WYB23.png Each of my own JS files follows a similar pattern, like this: $(function () { var init = function () { ...

Click event to verify, delete, and include class identifier in angular13

Looking to enhance functionality by dynamically adding and removing the 'active' class to 'li a' elements on click. While the current code performs well when clicking from top to bottom, it fails to work in reverse order. component.htm ...

Having difficulty implementing pagination functionality when web scraping using NodeJS

Currently, I am creating a script that scrapes data from public directories and saves it to a CSV file. However, I am encountering difficulties when trying to automate the pagination process. The source code I am using includes: const rp = require(' ...

Creating a unique texture on a spherical object using THREE.js

Can a sphere be textured in sections rather than all at once? Just like we can use 6 textures on 6 sides of a cube, is it possible to apply different textures to different parts of a sphere? For example, dividing the sphere into quarters and texturing each ...

What is the best way to generate inner HTML components within Angular by creating components?

I want to create a custom component that functions similarly to Material Tabs. I currently can use Material Tabs to create tabs like this <mat-tab-group mat-align-tabs="center"> <mat-tab label="First Tab"> <p& ...

Incorporate a customizable month option within a flexible calendar design

I'm working on creating a calendar that adjusts to different screen sizes for my website. The script I've implemented is as follows: <script type="text/javascript"> $(document).ready(function () { $(".responsive-calendar").responsiv ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

In TypeScript, the argument 'xxx' cannot be passed to a parameter expecting a 'string' type

When I try to create a new Error object with the message {code: 404, msg: 'user is not existed'} in TypeScript, I receive the following error message: [ts] Argument of type '{ code: number; msg: string; }' is not assignable to paramete ...

Passport Node: Issue with Password Comparison results in an undefined function error, causing return done(null, user) to fail

I have reviewed all the relevant inquiries and responses but I am still unable to resolve this issue. Please see the code provided below and assist me in understanding why the terminal is displaying 'undefined is not a function'. Here is an overv ...

A unique technique for creating a stunning visual effect with images using

Can anyone help me with this issue: Check out this animated GIF The images in my project are overlapping when scrolling! How can I achieve a similar effect for my images? Is there a tutorial or plugin available for this? Here is the current code sn ...

Why is the 3rd argument necessary when using useReducer?

According to the information provided in the documentation: [init, the 3d argument] allows you to separate the logic for determining the initial state outside of the reducer. This is particularly useful for resetting the state later in response to an ac ...

Oops! The Route.post() function is looking for a callback function, but instead, it received an [object Object

Looking to integrate a password reset feature in my web app, but encountering the error mentioned in the title. Here's a snippet of my code: main.js: const router = express.Router(); const AsyncNewPassword = require('./controller/asyncnewpasswor ...

Exploring TypeScript implementation of Redux toolkit's store

I'm currently diving into the world of Redux in React + TypeScript by following the tutorials provided by Redux Toolkit. I am attempting to implement it in a sample application. My main struggle lies with typings related to the store and the mappStat ...

Is there a way to incorporate the Indian rupee symbol into a Google chart?

I've been trying to incorporate the Indian Rupee symbol into a Google chart using the code below: var formatter = new google.visualization.NumberFormat({ prefix: '&#8377;' }); However, I'm encountering an issue where ...

Getting the data from the final day of every month in a Typescript time-series object array

I am dealing with timeseries data retrieved from an API that consists of random dates like the following: [ { "id": 1, "score": 23, "date": "2023-08-30" }, { "id": 2, "score&qu ...

Double quotes in JSON are not being escaped properly

When I try to evaluate some json on a screen, I keep encountering errors with the message 'unexpected identifier'... The problematic data that seems to be causing this issue is: "itemDescription":"STANDARD \"B\" RED BOX", To address ...