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

Connecting factors

Let me simplify what my code does: var list = { "group":{ "subgroup1":[{"name1":"Jimmy","name2":"Bob"}], "subgroup2":[{"name1":"Sarah","name2":"Nick"},{"name1":"Kevin","name2":"George"}] } } function group(group,name){ var link ...

Displaying varied information based on JSON feedback using AngularJS

I am currently in the process of developing an app using AngularJS and the Ionic framework. The app will display a list of data with various subcategories for each item, depending on the account type. View sample image here The issue I am facing is that ...

The functionality of @Output and custom events appears to be malfunctioning

I am a beginner in Angular and attempting to pass data between child and parent components. In the child component.ts file: @Output() doubleClick = new EventEmitter<string>(); onDoubleClick(nameAccount: string){ this.doubleClick.emit(nameAccoun ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

The IntrinsicAttributes type does not contain a property called 'theme'

As a junior TypeScript developer, I am exploring the creation of a dark mode feature using styled-components and a custom hook in TypeScript. useDarkMode.tsx import { useState } from 'react'; export const useDarkMode = () => { const [theme ...

Native JavaScript does not handle AJAX responses correctly

I'm facing an issue with my ajax call where the returned HTML works well on changes, but the Javascript that should perform actions based on clicks within the results is not functioning properly. Here is the ajax call: function update_order_shipp ...

Horizontal navigation bar encroaching on slideshow graphics

I'm encountering difficulties aligning the horizontal menu below the image slider. When I have just an image without the slider, the menu aligns properly (vertically), but as soon as I introduce the code for the slider, the menu moves to the top and d ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

How do you define prop types when passing them in Nextjs?

Welcome to my page import { InferGetServerSidePropsType, GetServerSideProps } from 'next' import ProductList from '../../component/product/ProductList' export interface Item { title: string price: number } const products ...

Alert: TypeScript Linter Warning

When I execute the npm lint command in Circle CI, a warning message is displayed. The following rules specified in the configuration could not be found: templates-use-public no-access-missing-member invoke-injectable template-to-ng-templa ...

Mixing pipe operators with Angular Observables in an array

In my project, I have an interesting scenario where I am using Observables and piping them to multiple functions as shown below. getOrders(filters: any, page: any = 1, orderBy: string = 'deliver_on', sort: string = 'asc') { const op ...

Utilizing Angular Services - registering to component OnDestruction

I have a service called MyService which is injected into the MyComponent. My goal is for MyComponent to be able to call a function on MyService and provide a way to reference this specific instance of MyComponent so that MyService can detect when the compo ...

MariaDB won't generate JSON output for a column that has a JSON data type

Currently, I am utilizing MariaDB and phpMyAdmin to effectively manage my database. Within one of my tables, I have a specific field that is defined as type json, or alternatively longtext. However, whenever I execute a SELECT query using JSON_EXTRACT(fiel ...

Showing attributes of models using Sequelize and Handlebars

As a novice in the world of programming, I am currently immersed in a website project where users can write and post articles. One crucial aspect I am focusing on is displaying the history of articles written by each user on their account page. Despite uti ...

How can I change the text of a single button by clicking on it without affecting the other buttons that share the same

Currently, I am implementing a posting system where posts can be added using a button. The posts have two additional buttons - one to show/hide content and the other to delete content. I am utilizing jQuery's slideToggle event to toggle the visibility ...

Guide to retrieving and showing specific items from a DropDownList in a Text box using JavaScript, HTML, and AngularJS

Can someone explain how to extract and select items from a DropDownList and display them in a Textbox using JavaScript/HTML/AngularJS? Here are more details: I have a dropdown list with many items. When I click on an item from the list, it should be dis ...

Prevent the need to go through the keycloak callback process each time the page is

I have integrated keycloak as an identity provider into my React application. I successfully added the keycloak react dependency via npm. Below are the versions of the keycloak react npm modules on which my application depends : "@react-keycloak/web ...

Searching for a solution on how to retrieve data server-side in the newest version of Next.js? Attempted to use getStaticProps but encountering issues with it not executing

Currently tackling a project involving Django Rest Framework with Next.js, and encountering a roadblock while trying to fetch data from the API. Data is present at the following URL: http://127.0.0.1:8000/api/campaigns, visible when accessed directly. The ...

Prevent TypeScript from allowing strings or arrays to be assigned to types with no properties

Can we limit the input for param so that it does not allow strings, arrays, etc.? interface bar { x?: number; y?: string; } function qux(param: bar) { } qux("hello"); ...

What could be causing the slow compilation of my Next.js pages within the app directory, and what steps can be taken to improve the speed of this

Currently, I am working on a Next.js project that uses the 'app' directory structure. However, during local development, I have been facing significant delays in compile times. Here's a breakdown of the compile times I am encountering: - Th ...