问题
json structure :
{
"Employee": [
{"id":1,"name":"Dan" },
{"id":2,"name":"Stack" },
.....
]
}
app.component.ts:
ngOnInit() {
console.log("first", "Test");
this.globalReader.getObjectData()
.subscribe(data => this.getData = JSON.stringify(data), ---> Response printed successfully here.I'm able to print it in label.
error => alert(error),
() => console.log("finished")
);
}
Edit:
component:
<label text ="{{getData }}" ></label>
getObjectData() {
return this._http.get('/page/emp.json')
.map((response :Response) => response.json());
}
After that I don't know how to parse the json and print it in listview for this structure. I referred some videos and grocery application. But I'm unable to get the result still.I'm very much confused with arrayname Employee.
I need to print only the name
from response in listview.
回答1:
This should work:
<ListView [items]="employees" row="1">
<template let-item="item">
<Label [text]="item.name"></Label>
</template>
</ListView>
// Create Employee Class:
export class Employee {
constructor(public id: string, public name: string) {}
}
// Your component:
this.employees: Array<Employee> = [];
ngOnInit() {
this.globalReader.getObjectData()
.subscribe(data => {
this.employees = data.Employee.map(item => new Employee(item.id, item.name);
});
});
}
// The getObjectData method of *globalReader* service:
getObjectData() {
return this._http.get('/page/emp.json')
.map((response :Response) => response.json().data);
}
Depending on the object returned by the http call, the .data may not be required:
getObjectData() {
return this._http.get('/page/emp.json')
.map((response :Response) => response.json());
}
回答2:
You need to map the data instead of Strigify data
this.globalReader.getObjectData()
.subscribe(data => this.getData = data.employee.map(e => e.name))
You can get it like following :
<ListView [items]="getData">
<template let-item="item">
<StackLayout>
<Label [text]='"ID: " + item.id'></Label>
<Label [text]='"Name: " + item.name'></Label>
</StackLayout>
</template>
</ListView>
来源:https://stackoverflow.com/questions/44629179/how-to-parse-this-json-structure-in-listview-angular2-nativescript