[英]Access nested json object angular 6
I'm trying to access the nested data from the HTML template, but I get undefined or I get nothing as result (empty page with no class list or student list).我正在尝试从 HTML 模板访问嵌套数据,但我得到未定义或我没有得到任何结果(没有 class 列表或学生列表的空页面)。
The HTML template: HTML 模板:
<div class="container">
<label *ngFor="let class of listClass | keyvalue">
<span> {{class.value.name}} </span>
</label>
<div>
<label *ngFor="let student of class.students | keyvalue">
<span>{{student.value.fullName}} </span>
</label>
</div>
</div>
This is the fonction that gets the list of class and the students in it:这是获取 class 和其中的学生列表的函数:
getListClasseStudent(){
this.classService.getStudents().subscribe((data) => {
this.listClass = data;
});
}
The nested data:嵌套数据:
class:
0:{
code: "Math01"
teacher:
0: {id: 17551, name "Jack"}
students:
0: {studentId: 1, fullName: "Patrick bob"}
1: {studentId: 2, fullName: "Alice Alice"}
}
1:{
code: "English01"
teacher:
0: {id: 2, name "Nicolas"}
students:
0: {studentId: 1, fullName: "Patrick bob"}
1: {studentId: 2, fullName: "Alice Alice"}
}
I want to access to the list of student of each class, is there any efficient way to do it?我想访问每个 class 的学生列表,有什么有效的方法吗? thanks in advance.
提前致谢。
<div class="container">
<div *ngFor="let c of listClass ">
<label >
<span> {{c.code}} </span>
</label>
<div>
<label *ngFor="let student of c.students ">
<span>{{student.fullName}} </span>
</label>
</div>
</div>
Try this (example without your pipe)试试这个(没有你的管道的例子)
A 'Class' object don't have a attribute 'value.name' (probably gonna be injected by your pipe '| keyvalue' ). 'Class' object 没有属性 'value.name' (可能会由您的 pipe '| keyvalue' 注入)。 Second *ngFor need t be inside of first, because he need's to iterate a students array, inside each class.
第二个 *ngFor 不需要在第一个内部,因为他需要在每个 class 内部迭代一个学生数组。
I hope this helps.我希望这有帮助。
create a pipe like below创建一个 pipe 如下所示
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
transform(value: Object): Array<string> { return Object.keys(value); }
}
import the above pipe in app.module.ts and use pipe in the html page like below在 app.module.ts 中导入上述 pipe 并在 html 页面中使用 pipe 如下所示
<div *ngFor="let key of questions | ObjNgFor" class="row">
{{ questions[key].name}}
<div *ngFor="let r of questions[key].sub_sections | ObjNgFor ; let indx=index"
class="card-body">
{{ questions[key].sub_sections[r].name }}"
</div>
This example should work这个例子应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.