Search code examples
angulartypescriptnativescriptangular2-servicesangular2-nativescript

How to parse this json structure in listview angular2 nativescript


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.


Solution

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