如何使用角度4显示前端的json

时间:2018-05-18 08:29:48

标签: json angular

我是角色4的新手。我在html视图中显示JSON时遇到问题。我跟随json。

{"result":[
{"role_id":124,"role_name":"ramesh","roles":"user"},
{"role_id":123,"role_name":"suresh","roles":"admin"}
]
}

组件文件

export class LoginComponent implements OnInit {
  data: Object;
  loading: boolean;
  credentials: Credentials;
  constructor(private http: Http) { }

  ngOnInit() {
    this.credentials = new Credentials();
  }
  login():void{
    console.log(this.credentials);

    this.loading = true;
    this.data = {};
    this.http.request('http://localhost:8080/api/Sampledata')
      .subscribe((res: Response) => {
        this.data = res.json();
        this.loading = false;
        console.log(this.data)
      });

  }
}

Html文件

<h2>Basic Request</h2>
    <button type="button" (click)="login()">Make Request</button>
    <div *ngIf="loading">loading...</div>
    <pre>{{data | json}}</pre>

我正在这样的前端获得json。 Front End Image

我想分别获取 role_name ,所以我尝试更改这样的html文件

<h2>Basic Request</h2>
    <button type="button" (click)="login()">Make Request</button>
    <div *ngIf="loading">loading...</div>
    <pre>{{data?.role_name}}</pre>
    </div>

只显示role_name的正确方法是什么?

3 个答案:

答案 0 :(得分:1)

您可以使用*ngFor,因为数据位于对象数组中。

<pre *ngFor="let res of data.result">{{res.role_name}}</pre>

答案 1 :(得分:0)

执行以下操作,列出您对象的每个属性

.subscribe((res: Response) => {
        this.data = res.json();
       if(this.data.result && this.data.result.length > 0)
        this.objekeys = Object.keys(this.data.result[0]);
        this.loading = false;
        console.log(this.data)
      });

<table>
   <tr *ngFor="let data of data.result">  
     <td *ngFor="let key of objekeys">
       <span>key </span> <span>data[key]</span>
     </td>
   </tr>
</table>

答案 2 :(得分:0)

您可以使用索引

访问特定元素
<h2>Basic Request</h2>
    <button type="button" (click)="login()">Make Request</button>
    <div *ngIf="loading">loading...</div>
    <pre>{{data.result[0]?.role_name}}</pre>
    </div

如果您想列出所有名称,请使用*ngFor

<h2>Basic Request</h2>
        <button type="button" (click)="login()">Make Request</button>
        <div *ngIf="loading">loading...</div>
         <pre *ngFor="let r of data.result">{{r.role_name}}</pre>
     </div>

<强> DEMO