1
votes

I'm trying to display data from my json file but I have an error that I can't find a solution to, despite my research on stackoverflow.

i have this error: 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"
    },
]
}

ts.file

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

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

interface

export interface Ipost {
  id:number,
  mnemo:string,
  libelle:string,
  bigramme:string
}
1
The error message is clear. The array is contained in the flags property of the postArray variable. Try: *ngFor="let post of postArray?.flags". The safe navigation operator ?. will check if the postArray variable is defined before accessing it's property flag. - Michael D
OR based on your variable declaration, you need to initialize it with the flags property in the subscription: this.postArray = result['flags']. In this case, the template doesn't need any change. - Michael D

1 Answers

0
votes

You have to modify postArray to postArray.flags in *ngFor. because postArray refers to the Whole Json object which is not an array, but postArray.flags is the array you want to reach out to.

Initialise Ipost like below in ts file

postArray: Ipost[] = undefined;

and change template code like 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>