我对角4很陌生,我在html视图中显示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放在前头。前端图像
我想单独获得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呢?
发布于 2018-05-18 08:45:16
可以使用索引访问特定的元素。
<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>发布于 2018-05-18 08:36:21
您可以使用*ngFor,因为数据位于对象数组中。
<pre *ngFor="let res of data.result">{{res.role_name}}</pre>发布于 2018-05-18 08:36:06
按下面的方式列出对象的每个属性
.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>https://stackoverflow.com/questions/50407000
复制相似问题