Issue encountered while attempting to differentiate 'object Object'. NgFor only permits arrays and iterables

Having a JSON file containing a list of properties for sale, I am attempting to utilize *NgFor to iterate through the data and generate a list.

Being relatively new to Angular and app development, there's a possibility that I might have misunderstood some documentation or concepts.

I've experimented with looping through different paths:

*NgFor="let post of posts.properties"
*NgFor="let post of posts.properties.property"

But, I'm still encountering various errors.

My understanding is that I need to cast the observable to an array of properties and then bind it to the HTML. (I believe I've already done this since 'properties' is of type array?)

Here's a snippet of the JSON data:

{
    "properties": {
        "property": [
            {
                "propertyID": "101552000007",
                "branchID": "1",
                "clientName": "A Demo",
                "branchName": "Brackley",
                "department": "Sales",
                "referenceNumber": "10006",
                "addressName": "",
                "addressNumber": "87",
                "addressStreet": "Hackney Road",

And here's the 'properties.interface.ts' file:

export interface IProperties {
    addressStreet: string;
    addressNumber: number;
}

The 'for-sale.service.ts' file looks like this:

import { IProperties } from './../properties.interface';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';



@Injectable({
  providedIn: 'root'
})
export class ForSaleService {

  constructor(private http: HttpClient) {}

  getProperties(): Observable<IProperties[]> {
    return this.http.get<IProperties[]>('/assets/data/jupix.json');

  }

}

And now we have the 'for-sale.page.ts' file:

import { ForSaleService } from './for-sale.service';
import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-for-sale',
  templateUrl: './for-sale.page.html',
  styleUrls: ['./for-sale.page.scss'],
  providers: [ForSaleService]
})
export class ForSalePage implements OnInit {

  public properties = [];

  constructor(private saleService: ForSaleService) {}

  ngOnInit() {
    this.onGetProperties();
  }

  onGetProperties() {
    this.saleService.getProperties()
      .subscribe(response => {
        console.log(response);
        this.properties = response;
      });
  }
}

Lastly, the HTML part:

<ion-content>
  <ion-list *ngFor="let property of properties">
    <ion-card>

      <ion-card-header>{{ property.addressNumber }}</ion-card-header>
      <ion-card-content>
        <p>
          <ion-icon name="person" color="primary"></ion-icon>
        </p>
      </ion-card-content>
    </ion-card>
  </ion-list>
</ion-content>

I seem to be facing issues with binding 'let property of properties' to the array of properties?

UPDATE: Despite trying out a few suggestions, a consistent error pattern seems to be emerging in the console log? It appears to be recognizing child elements as undefined, leading to these errors?

To make things clearer, I changed the variable completely to 'propertiesList.'

A strange occurrence is happening now.

When using

*ngFor="let property of propertiesList.properties.property"
,

and for the card image

<img src="{{ property.images.image[0].__text }}" alt="">
The image displays correctly, but the console shows
Cannot read property '__text' of undefined
, along with the original
" Cannot read property 'property' of undefined

Continuing to add other elements in the HTML:

<ion-card-header>{{ property.addressNumber }} {{ property.addressStreet }} {{ property.addressPostcode }}</ion-card-header>

These sections are working fine without any errors, displaying the data properly. But something interesting occurs next.

<p>{{ property.propertyFeature1 }} {{ property.floorplans.floorplan._modified }}</p>

Adding this piece, the error

Cannot read property '__text' of undefined
disappears, and is replaced by
Cannot read property '__modified' of undefined
alongside the original
Cannot read property 'property' of undefined

In Visual Studio Code, the only error I'm receiving is

Identifier 'properties' is not defined. 'Array' does not contain such a member

Answer №1

According to the information provided in the resources:

An object becomes iterable when it specifies its own way of iteration, determining which values can be looped over using a for...of construct. Certain pre-defined types like Array or Map come with default methods of iteration, while others such as Object do not.

In order to make it iterable, modify the ngFor directive as follows:

<ion-list *ngFor="let item of items.item">

This adjustment will allow you to iterate through it since it functions as an array.

Answer №2

Give this a shot!

Prior to looping through, make sure to validate the

*ngIf="properties.properties.property?.length > 0"
condition to confirm if the array or object is empty.


<ion-content *ngIf="properties.properties.property?.length > 0">
   <ion-list *ngFor="let property of properties.properties.property">
       <ion-card>

        <ion-card-header>{{ property.addressNumber }}</ion-card-header>
        <ion-card-content>
          <p>
           <ion-icon name="person" color="primary"></ion-icon>
          </p>
        </ion-card-content>
      </ion-card>
   </ion-list>
  </ion-content>

This will help you avoid encountering errors in the console such as

Cannot read property 'property' of undefined

I trust that this information will prove to be beneficial.

Answer №3

In my opinion, the GET request may not be able to correctly map your data to the properties defined in your Interface. If the mapping is incorrect, it will not be a valid array that can be looped over.

Based on the variables you provided, you should loop over it like this:

<ion-list *ngFor="let property of properties.properties.property">

Consider using "properties" as your result array, then "properties" as a property of the JSON object + "property" as an actual array with data. It's uncertain if using these identical identifiers will work as intended.

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

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

Typescript validation of tokens using Azure functions

Currently working on a website utilizing Azure Static Web App, where the login/registration is managed by Azure B2C. The backend API consists of typescript Azure functions integrated with Azure Static web app. Certain API calls can only be accessed when th ...

Guide to resolving the issue of DELETE error 404 not found in express.js

I enrolled in a MEAN Stack course and have been making progress. I can easily add new data and fetch existing data, but running into trouble when attempting to DELETE data. The error message reads as follows: "DELETE http://localhost:3200/posts/5e831685bf7 ...

Ways to restrict the values allowed in a TypeScript type?

I have a requirement: type AllowedKeys = 'a' | 'b' | 'c' ... and now I want to define a type where the key has to be one of the values in AllowedKeys. For example: type MyType = { a: number; b: string; c: boolean; d: {} / ...

Difficulty establishing a connection between Typescript and Postgres results in a prolonged

I am attempting to establish a connection to a Postgres database using typescript. For the ORM, I have opted for sequelize-typescript. The issue lies in the fact that the script seems to hang at await sequelize.sync();. Below is the content of the sequeliz ...

Getting into a dynamic named property inside another object in angular can be achieved by utilizing bracket notation

I encountered an issue in my Angular 8 project where I create an object from a JSON, but there is a dynamic property whose name is unknown until runtime. This causes problems when trying to access the value of that dynamic property within another object, l ...

Typescript error: The property "Authorization" is not found in the type HeadersInit

As I utilize the npm module node-fetch, I have a helper function specifically designed to facilitate authorized requests to a third-party service. This function essentially acts as middleware by incorporating the Authorization header. async function makeAu ...

Enhancing Material UI v4 Themes using TypeScript

I am attempting to implement my own custom palette option in the theme section, but I am struggling with how to do the augmentation part using TypeScript. So far, I have created a file named "material-ui.d.ts" and inside it, I only have: import { PaletteO ...

Creating an Angular FormControl that can toggle multiple buttons

Here is the object I am currently working with currentApplication = { 'Initial': [12, 2, true, true, false], 'Reminder1': [8, 2, true, true, false], 'Reminder2': [4, 2, true, true, false], ...

Encountering Error: Unable to create new component as PriorityQueue is not recognized as a constructor

While trying to create a new component using Angular CLI with the command ng g c navbar, I encountered an unusual error message: core_1.PriorityQueue is not a constructor TypeError: core_1.PriorityQueue is not a constructor at new TaskScheduler (/h ...

Combining arrays of objects sharing a common key yet varying in structure

Currently, I am facing a challenge while working on this problem using Typescript. It has been quite some time since I started working on it and I am hoping that the helpful community at StackOverflow could provide assistance :) The scenario involves two ...

Invoke the built-in matcher within a Playwright custom matcher

I am in the process of implementing a custom matcher for Playwright based on the information provided in the official documentation on extending expect. In a similar vein to this unanswered discussion, my goal is to invoke an existing matcher after modifyi ...

Prevent automatic submission of forms when selecting attributes in HTML forms using AngularJS

I need to create a form where users can select their branch of study. Here is the form I have designed- <form method="post" [formGroup]="formData" (click)="dataSubmit()" > <div class="form-group"> <label for="branch">Selec ...

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

Tips for getting links to wrap or scroll within a column element in Angular

In my row element with two columns, I am facing an issue where the first column sometimes overlaps the second column due to a very long link in the problem.problem_description section. I want to find a way to have long links wrap or be scrollable. However, ...

How to host an Angular 2 application on IIS-10 without using ASP.NET Core

I've managed to create a plane angular-2 application using webpack in Visual Studio 2015 and now I'm looking to deploy it on IIS-10. Since I didn't use the ASP.NET Core template for this project, I need guidance on how to properly deploy thi ...

Handling JSON Objects with Next.js and TypeScript

Currently, I am working on a personal project using Next.js and Typescript. Within the hello.ts file that is included with the app by default, I have added a JSON file. However, I am facing difficulties in mapping the JSON data and rendering its content. T ...

Testing Angular HTTP error handlers: A comprehensive guide

Below, you will find an example of code snippet: this.paymentTypesService.updatePaymentTypesOrder('cashout', newOrder).subscribe(() => { this.notificationsService.success( 'Success!', `Order change saved successfully`, ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

Difficulties in Networking Requests Following Event Emitter Notification in an Angular Application

Within my Angular application, a network request is sent to retrieve filtered data based on user-selected filters. The function responsible for handling the filter values and executing the request is outlined as follows: public onFilterReceived(values) { ...