如何在Angular 4前端单独展示JSON中的role_name字段
解决Angular 4中单独展示JSON数组内字段的问题
嘿,别担心,这是Angular新手常遇到的小问题,我来帮你捋清楚!
你已经成功获取到了完整的JSON数据,但问题在于你的数据结构里,role_name是嵌套在result这个数组里的,而不是直接挂在data对象上。所以直接访问role_name肯定拿不到值,得先遍历result数组才行。
具体实现步骤
- 确认数据结构:你的返回数据结构是这样的:
{"result":[{"role_id":124,"role_name":"ramesh","roles":"user"},{"role_id":123,"role_name":"suresh","roles":"admin"}]}
也就是说,data.result才是存储用户角色数据的数组,每个数组元素包含role_name字段。
- 修改HTML模板:用
*ngFor指令遍历data.result数组,同时用*ngIf做空值判断(避免数据未加载时出现报错):
修改后的HTML代码如下:
<h2>Basic Request</h2> <button type="button" (click)="login()">Make Request</button> <div *ngIf="loading">loading...</div> <!-- 新增:遍历result数组显示role_name --> <div *ngIf="data && data.result"> <h3>角色名称列表</h3> <ul> <li *ngFor="let role of data.result"> {{ role.role_name }} </li> </ul> </div> <!-- 保留原来的完整JSON展示(可选) --> <pre>{{data | json}}</pre>
代码解释
*ngIf="data && data.result":确保当data和data.result都存在时才渲染这部分内容,防止组件初始化时data还未赋值导致的undefined错误。*ngFor="let role of data.result":循环遍历result数组,把每个元素赋值给role变量。{{ role.role_name }}:直接访问当前遍历项的role_name字段,展示具体值。
可选优化:定义数据类型(更规范的写法)
为了让代码更清晰,你可以在组件里定义一个接口来描述角色数据的结构:
// 在LoginComponent上方定义接口 interface Role { role_id: number; role_name: string; roles: string; } interface ApiResponse { result: Role[]; } // 然后修改组件里的data类型 export class LoginComponent implements OnInit { data: ApiResponse; // 这里改成ApiResponse类型 loading: boolean; credentials: Credentials; constructor(private http: Http) { } ngOnInit() { this.credentials = new Credentials(); } login():void{ console.log(this.credentials); this.loading = true; this.data = {} as ApiResponse; // 初始化时指定类型 this.http.request('http://localhost:8080/api/Sampledata') .subscribe((res: Response) => { this.data = res.json() as ApiResponse; this.loading = false; console.log(this.data) }); } }
这样TypeScript会帮你做类型检查,避免拼写错误,代码可读性也更高。
内容的提问来源于stack exchange,提问作者Jerold
相关产品推荐
相关产品推荐

