如何以Angular 2中的表格访问JSON对象属性

时间:2017-01-17 07:15:01

标签: json angular typescript

我是Angular 2的新手,并尝试从API访问数据。作为输出,我在浏览器上获得API响应作为所有JSON对象。但我不知道如何访问各个属性。下面是我的代码:

test.component.ts

function checkContainer () {
  if($("div").is(':visible'))){
    createGrid();
  }else {
    setTimeout(checkContainer, 50);
  }
}

test.service.ts

import { Component, OnInit } from '@angular/core';
import { HttpTestService } from './http-test.service';

@Component({
  selector: 'http-test',
  templateUrl: './http-test.component.html',
  providers: [HttpTestService]

})
export class HttpTestComponent implements OnInit {

  getData:string;
  postData: string;

  constructor(private _httpService: HttpTestService) { }

  getTest(){
    this._httpService.getData()
        .subscribe(
            data => this.getData = JSON.stringify(data) 
        );
  }

  ngOnInit() {
  }

}

test.component.html

在这个文件中,当我使用import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class HttpTestService { constructor(private _http: Http) { } getData(){ return this._http.get("http://jsonplaceholder.typicode.com/users") .map(res => res.json()) } } 时,我获得了整个JSON对象,但当我尝试访问其任何属性时,我得到了ERROR

{{getdata}}

app.module.ts

<button (click)="getTest()">Get Result</button>
output: 
<ul>
<li>{{ getData[0][time] }}</li>
</ul>

**输出:** This is my output, and I want to access its individual property (like..email) as list

2 个答案:

答案 0 :(得分:4)

this.getData = JSON.stringify(data)会使您的对象成为字符串,并且您无法访问字符串字段,如对象。去掉它。

然后您需要以“{1}}密钥作为”字符串“

尝试:

time

<li>{{ getData[0]['time'] }}</li>

示例:http://plnkr.co/edit/CB3oGppm4fvoEExfDSRc?p=preview

答案 1 :(得分:3)

更改您在plunker中的代码,如下所示:

    import { Component } from '@angular/core';
    import { ConfigurationService } from './ConfigurationService';


    @Component({
      selector: 'my-app',
      template: `

        <table>
        <tr *ngFor="let data of getData">
          <td>{{data.address.street}}</td>
          <td>{{data.address.geo.lat}}</td>
          <td>{{data.name}}</td>
          <td>{{data.email}}</td>
        </tr>
        </table>
      `
    })
    export class AppComponent {
      getData : any[] ;

       constructor(private _ConfigurationService: ConfigurationService)
        {
            console.log("Reading _ConfigurationService ");
            //console.log(_ConfigurationService.getConfiguration());

             this._ConfigurationService.getConfiguration()
                .subscribe(
                (data)=> {
                    this.getData = data; 
                    console.log(this.getData);
                },
                (error) => console.log("error : " + error)
            );

        }


    }