Oops! An error has occurred while attempting to differentiate '[object Object]'. Please note that only arrays and iterables are permitted in Angular

I'm encountering an issue while attempting to showcase data from my JSON file. Despite extensively researching on StackOverflow, I am unable to find a solution to the error at hand.

The error message reads: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

JSON

{
  "flags": [
    {
      "id": 1,
      "mnemo": "KHM",
      "libelle": "Cambodge",
      "bigramme": "KH"
    },
    {
      "id": 2,
      "mnemo": "KHM",
      "libelle": "France",
      "bigramme": "FR"
    },
]
}

Typescript File (.ts)

export class HomepageComponent implements OnInit {

  postArray: Ipost[] = [];

  constructor(private homeService: HomeService, private router: Router) { }

  ngOnInit(): void {
    this.getAllNations();
  }

  getAllNations() {
    this.homeService.getAll().subscribe(result => {
      this.postArray = result;
      console.log(this.postArray);
    });
  }    
}

HTML Template

<div class="col-1 px-0" *ngFor="let post of postArray">
      <div *ngIf="post.id >= 13">
        <span>{{post.libelle}}</span>
      </div>
    </div>

Interface Definition

export interface Ipost {
  id:number,
  mnemo:string,
  libelle:string,
  bigramme:string
}

Answer №1

In order to access the array within the postArray object in *ngFor, you need to change postArray to postArray.flags. This is because postArray refers to the entire Json object, whereas postArray.flags specifically targets the array you are looking for.

To initialize Ipost in your ts file, use the following code snippet:

postArray: Ipost[] = undefined;

Update the template code as shown below:

<ng-container *ngIf="postArray">
    <div class="col-1 px-0" *ngFor="let post of postArray?.flags">
          <div *ngIf="post.id >= 13">
            <span>{{post.libelle}}</span>
          </div>
        </div>
    </ng-container>

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 is the best way to extract the information from an ion input field?

I've tried this out: this.updatedValue = document.getElementById("processID"); this.updatedValueString = this.updatedValue.value; console.log("[INFO] Selected processID: >" + this.updatedValueString + "<"); But, I'm receiving this in logc ...

What could be causing my application to not locate the jquery module? ERROR: ENOENT: The specified file or directory cannot be found

I've decided to bring over an Angular project that already has a bootstrap template integrated into my own project. (Still unsure if this was the right move) One of the steps I took was adding these lines to the angular.json file: "styles": [ ...

Excluding spec files from code coverage in Angular: A step-by-step guide

I'm seeking to determine the code coverage of my Angular project, but I lack expertise in the tools needed. In an attempt to address this issue, I opted for using "istanbul-instrumenter-loader": "^3.0.1". I attempted to seek guidance from a relevant q ...

Highcharts Angular experiencing issues with DataGrouping

In my current angular 11 project, I have the following dependencies listed in my package.json file: "dependencies": { ... "highcharts-angular": "^2.10.0", ... My goal is to display a chart with dates on the x-axis ...

Customizing react-day-picker to display upcoming week

I have created a component that displays only the "week view." Currently, it is set up to show the current week. You can find the code for this implementation in this URL: How to customize react-calendar to show only one week at a time? "use client&qu ...

Transfer information to a form using the <mat-select> element

Looking for a way to display user roles in Angular using a mat-table that were previously selected with <mat-select>. When I use a regular <select>, a new entry shows up in the table, but the styling is not ideal. <label>Role</labe ...

Navigating through an array in Angular 5: a guide

This question may seem simple, but I'm having trouble figuring it out. Here is the code snippet I am working with: getInstabul(): void { this.homeService.getWeather() .subscribe((weather) => { this.instanbulWeathers = weather ...

rxjs - straightforward issue with initiating observables

I'm currently tackling an assignment that involves setting up a basic form with input fields for 'From', 'To', and 'Duration' using rxjs. While it might be easier to just utilize getter / setters, I'm determined to ...

Facing issues with building Angular 7 and Ionic 4 - getting error message "TypeError: Cannot read properties of undefined (reading 'kind')"

I need assistance with a problem I am encountering while building my Angular 7 & Ionic 4 application... When I run the ng build --prod command, I encounter the following error: ERROR in ./node_modules/ionic4-auto-complete/fesm5/ionic4-auto-complete.js ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Can you explain the purpose of the "=" symbol in the function definition of "export const useAppDispatch: () => AppDispatch = useDispatch" in TypeScript?

Recently, while working on a React app that utilizes react-redux and react-toolkit, I encountered some TypeScript syntax that left me puzzled. export type RootState = ReturnType<typeof store.getState> export type AppDispatch = typeof store.dispatch e ...

Parsing errors occurred when using the ngFor template: Parser identified an unexpected token at a specific column

In my Angular CLI-built application, I have a component with a model named globalModel. This model is populated with user inputs from the previous page and displayed to the user in an HTML table on the current page. Here's how it's done: <inp ...

Firestore data displaying as null values

Recently, I encountered CORS errors while polling the weather every 30 seconds in my program. Upon investigating, I discovered that the city and country were being interpreted as undefined. To fetch user data from my users' table, I utilize an Axios ...

Having trouble with an Angular subscribe error that says "Property 'subscribe' does not exist on type 'AngularFireList<unknown>'.ts(2339)"? Let's find a solution together!

My goal is to retrieve data from a Firebase RDB in the data service by using the following function: this.getOrgId() .subscribe((orgId: string) => localStorage.setItem('orgId', orgId)); getOrgId() { return this.db.list(/users/${this.uId ...

Error message: Unable to associate with DIRECTIVE as it is not a recognized attribute of 'div'

Despite searching through similar questions about this error, I have not been able to find a solution. The issue arises with my highlight directive, which takes an input parameter index. Initially, the directive worked perfectly when declared within the m ...

Challenges encountered when testing middleware in a TypeScript Node.js Express project

I have been exploring the repository at https://github.com/goldbergyoni/nodebestpractices to enhance my understanding of nodejs best practices. Below is a middleware I developed: import { NextFunction, Request, Response } from "express"; import ...

Can Realm be integrated with Angular 2 for development?

Exploring the compatibility of Realm Mobile Platform with an Angular 2 app has been quite challenging. It seems that integrating the Javascript version of Realm in Angular 2 is not straightforward. I managed to run npm install --save realm successfully and ...

Move on to a different screen in a React Component once the data has been fetched

Currently, I am delving into the world of React and TypeScript and attempting to utilize "react-router-dom" in order to create a login component that will interact with my backend server. Essentially, my goal is to develop a "Login" class that, upon form ...

Discover the versatility of TypeScript by dynamically adding methods to a class!

Are there any examples of dynamically extending a class with a method in TypeScript? I attempted the following: UsersBlocksMyOrders.prototype.myFunc = function():any{ alert('23434'); }; However, the compiler is giving me an error. ...

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...