Aneez
Aneez

Reputation: 61

Angular2 : Read JSON file using http get

I am trying to read a json file using http get but I am getting below error.

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

please help me on what is wrong.

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { peopleService } from './PeopleService';


@Component({
selector: 'my-app',
templateUrl: './app.component.html',
//providers: [peopleService]
})

export class AppComponent {
//jsonFile: string = './EmployeeHeader.json';
empdata: Observable<Array<any>>[];

constructor(private http: Http) {
    this.http.get('../assets/EmployeeHeader.json')
        .map(Response => Response.json())
        .subscribe(empdata => this.empdata = empdata, error => console.log(error));
    //this.empdata = service.getPeople();
    //console.log('Data is: ' + this.empdata);
}
}

Adding the HTMl part below for reference,

<tbody>
<tr *ngFor="let t of empdata">
<td>{{t.wwid}}</td>
<td>{{t.name}}</td>
<td></td>
<td></td>
<td></td>
<td>{{t.idsid}}</td>
<td></td>
</tr>
</tbody>

folder structure

JSON format of the code for your reference and I am not sure if any issue with this

   {
"Employee":
[
  {
    "name": "Karthik Shekhar",
    "wwid": "11597210",
    "idsid": "kshekh1x",
    "costCenterCode": "80790",
    "mgrWWID": "10693268",
    "orgUnit": "67926"
  },
  {
    "name": "Aneesur Rahman",
    "wwid": "11744439",
    "idsid": "aneesurx",
    "costCenterCode": "32406",
    "mgrWWID": "10693268",
    "orgUnit": "67926"
  },
  {
    "name": "Ashutosh Pandey",
    "wwid": "11691980",
    "idsid": "ashuto3x",
    "costCenterCode": "32406",
    "mgrWWID": "10693268",
    "orgUnit": "67926"
  },
]
}

Upvotes: 0

Views: 252

Answers (2)

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

change your service like below

  this.http.get('../assets/EmployeeHeader.json')
            .map(Response => Response.json())
            .subscribe(empdata => {this.empdata = empdata.Employee}
    , error => console.log(error));

or change the *ngFor to

<tbody>
<tr *ngFor="let t of empdata.Employee">
<td>{{t.wwid}}</td>
<td>{{t.name}}</td>
<td></td>
<td></td>
<td></td>
<td>{{t.idsid}}</td>
<td></td>
</tr>
</tbody>

Upvotes: 0

CozyAzure
CozyAzure

Reputation: 8468

Your empdata was an object, not an array. You need to access the Employee property in your object:

constructor(private http: Http) {
    this.http.get('../assets/EmployeeHeader.json')
        .map(Response => Response.json())
        .subscribe(empdata => {
            //access Employee property
            this.empdata = empdata.Employee
        }, error => console.log(error));
}

Upvotes: 2

Related Questions