如何在listview angular2 nativescript中解析这个json结构

时间:2017-06-19 11:18:21

标签: angular typescript nativescript angular2-services angular2-nativescript

json结构:

{
  "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")

      );      

  }

修改

组件:

  <label text ="{{getData }}" ></label>



  getObjectData() {

    return this._http.get('/page/emp.json')
      .map((response :Response) => response.json());

  }  

之后我不知道如何解析json并在listview中打印出这个结构。我推荐了一些视频和杂货申请。但是我还是无法得到结果。我对arrayname Employee非常困惑。

我需要在列表视图中仅打印响应中的name

2 个答案:

答案 0 :(得分:6)

这应该有效:

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

根据http调用返回的对象,可能不需要.data:

getObjectData() {
    return this._http.get('/page/emp.json')
        .map((response :Response) => response.json());
}

答案 1 :(得分:1)

您需要映射数据而不是Strigify数据

this.globalReader.getObjectData()
  .subscribe(data => this.getData = data.employee.map(e => e.name))

你可以得到如下:

<ListView [items]="getData">
    <template let-item="item">
        <StackLayout>
            <Label [text]='"ID: " + item.id'></Label>
            <Label [text]='"Name: " + item.name'></Label>
        </StackLayout>
    </template>
</ListView>