Angular2:使用http get读取JSON文件

时间:2017-07-12 07:04:44

标签: json angular

我正在尝试使用http get读取json文件,但我收到以下错误。

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

请帮我解决错误。

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);
}
}

添加下面的HTMl部分以供参考,

<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格式供您参考,我不确定是否有任何问题

   {
"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"
  },
]
}

2 个答案:

答案 0 :(得分:2)

您的empdata是一个对象,而不是一个数组。您需要访问对象中的Employee属性:

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));
}

答案 1 :(得分:0)

更改您的服务,如下所示

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

或 将* ngFor更改为

<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>