Getting an runtime error when using *ngFor on a JSON file


#1

I’m having a hard time importing the data from a json file into my ionic project. The structure of the file is shown in the image below.

@Injectable()
export class JsonProvider {

  public plan;

  constructor(public http: HttpClient, public file : File) {
    this.http.get('../assets/data/arbeidsplan.json').subscribe(data => {
      this.plan = data;
          });
    this.plan = Array.of(this.plan);
  }

}

When I insert the code below in my html file, I get the following Runtime Error: "Error trying to diff ‘object Object’. Only arrays and iterables are allowed.

<div *ngFor="let c of jsonProvider.plan">

</div>

#2

Hi @IonVis123123
You are doing it wrong.The error is clear that your are trying to iterate an object.
Iteration only possible with array.One solution is that push the object in to an array
and Iterate.Use array.push(this.plan);


#3

Hi @vibinflogesoft!

Thank you for your quick response. I have probably misunderstood you, but when I change my code, I get the runtime error “Cannot read property ‘push’ of undefined”.

@Injectable()
export class JsonProvider {

  public plan : any[];

  constructor(public http: HttpClient) {
    this.http.get('../assets/data/arbeidsplan.json').subscribe(data => {
      this.plan.push(data);
          });
  }

}

#4

Hey @IonVis123123
plan should be an array,then only you can perform push operation
Change this public plan : any[];
public plan:Array<any>=[];


#5

Thank you!

Now I get 1 div in the ngFor loop. But I would like to iterate over ID1, ID2, ID3 and ID4.