How to parse this json structure in listview angular2 nativescript

怎甘沉沦 提交于 2019-12-11 08:06:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!