[英]Angular2 : Read JSON file using http get
I am trying to read a json file using http get but I am getting below error. 我正在尝试使用http get读取json文件,但出现以下错误。
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, 在下面添加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>
JSON format of the code for your reference and I am not sure if any issue with this 代码的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"
},
]
}
Your empdata
was an object, not an array. 您的
empdata
是一个对象,而不是数组。 You need to access the Employee
property in your object: 您需要访问对象中的
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));
}
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 或将* 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.