[json] Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I've created an angular app which gets data from a json file. But I'm having issues with showing the data in html. A lot of variables are in dutch, I'm sorry for that. I'm also a bit new to all of this :)

This is my service:

import {Injectable} from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from "rxjs";
import {Afdelingen} from "./models";

@Injectable()
export class AfdelingService {
  private afdelingenUrl = '/assets/backend/afdelingen.json';
    constructor(private http: Http) {
      }

      getAfdelingen(): Observable<Afdelingen[]> {
        return this.http.get(this.afdelingenUrl)
          .map(this.extractData)
          .catch(this.handleError);
      }

      private extractData(res: Response) {
        let body = <Afdelingen[]>res.json();
        return body || {};
      }

      private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
      }

      addAfdeling(afdelingsNaam: string, afdeling: any): Observable<Afdelingen> {
        let body = JSON.stringify({"afdelingsNaam": afdelingsNaam, afdeling: afdeling});
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});
        return this.http.post(this.afdelingenUrl, body, options)
          .map(res => <Afdelingen> res.json())
          .catch(this.handleError)
      }
    }

This is part of my json file:

{
  "afdelingen": [
    {
      "afdelingsNaam": "pediatrie",
      "kamernummer": 3.054,
      "patientid": 10001,
      "patientennaam": "Joske Vermeulen",
      "reden": "Appendicitis",
      "opname": "12/05/2017",
      "ontslag": "28/06/2017",
      "behandelingstype": "nazorg",
      "behandelingsomschrijving": "wondverzorging",
      "behandelingsdatum": "10/06/2017",
      "behandelingstijd": "10:20",
      "vegitarisch": false,
      "Opmerkingen": "",
      "sanitair": true,
      "kinderverzorgingsruimte": false,
      "salon": true,
      "hulp": true,
      "width": 5,
      "height": 5
    },
    {
      "afdelingsNaam": "pediatrie",
      "kamernummer": 3.055,
      "patientid": 10002,
      "patientennaam": "Agnes Vermeiren",
      "reden": "Beenbreuk",
      "opname": "18/05/2017",
      "ontslag": "30/06/2017",
      "behandelingstype": "nazorg",
      "behandelingsomschrijving": "wondverzorging",
      "behandelingsdatum": "10/06/2017",
      "behandelingstijd": "10:20",
      "vegitarisch": true,
      "Opmerkingen": "",
      "sanitair": true,
      "kinderverzorgingsruimte": false,
      "salon": true,
      "hulp": false,
      "width": 5,
      "height": 5
    }]}

The Component:

import {Component, OnInit, Input} from '@angular/core';
import {Afdelingen} from "../models";
import {AfdelingService} from "../afdeling.service";
import {PatientService} from "../patient.service";


@Component({
  selector: 'app-afdeling',
  templateUrl: './afdeling.component.html',
  styleUrls: ['./afdeling.component.css']
})
export class AfdelingComponent implements OnInit {

 afdeling: Afdelingen[];
 errorMessage:string;

  constructor(private afdelingService: AfdelingService, private patientService: PatientService) { }

  ngOnInit() {
    this.getData()
  }

  getData() {
    this.afdelingService.getAfdelingen()
      .subscribe(
        data => {
          this.afdeling = data;
          console.log(this.afdeling);
        }, error => this.errorMessage = <any> error);

  }
}

and the html:

<ul>
  <li *ngFor="let afd of afdeling">
    {{afd.patientid}}
  </li>
</ul>

This question is related to json angular angular-services angular-ngfor

The answer is


You only need the async pipe:

<li *ngFor="let afd of afdeling | async">
    {{afd.patientid}}
</li>

always use the async pipe when dealing with Observables directly without explicitly unsubscribe.


I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

Remember to pipe Observables to async, like *ngFor item of items$ | async, where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair>, and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T.

Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty


Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular-services

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays' @HostBinding and @HostListener: what do they do and what are they for? Passing data between controllers in Angular JS? angular.service vs angular.factory AngularJS : How to watch service variables?

Examples related to angular-ngfor

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'