我有两个名为teachers
和sessions
的api。
teachers
JSON 文件:
[
{
"teacherName": "Binky Alderwick",
"id": "01"
},
{
"teacherName": "Basilio Gregg",
"id": "02"
},
{
"teacherName": "Binky Alderwick",
"id": "03"
},
{
"teacherName": "Cole Moxom",
"id": "04"
}
]
sessions
JSON 文件:
[
{
"id":"001",
"sessionName": "Chemistry",
"notes": "Chemistry is the study of matter, its properties",
"teacherIds": ["01","03"]<==========
},
{
"id":"002",
"sessionName": "Physics",
"notes": "Physics is the natural science that studies matter and its motion ",
"teacherIds": ["02","04"]
},
{
"id":"003",
"sessionName": "Maths",
"notes": "Mathematics includes the study of such topics as quantity",
"teacherIds": ["01","04"]<=========
},
{
"id":"004",
"sessionName": "Biology",
"notes": "Biology is the natural science that studies life and living organisms",
"teacherIds": ["02","04"]
}
]
现在,我正在这样显示模板中的所有教师:
在会话 JSON中,我提到了 teacherIDs ,该数组是数组,我想基于教师ID显示特定教师的会话。
对于以前的会话,(化学与数学)包含 teacherID 为(01),所以我想在老师1(i,e Binky)下显示这两个会话(化学与数学) Alderwick):
我应该基于session
获取teacherId
对象的所有属性。
答案 0 :(得分:2)
这可以在您的堆叠闪电战中发挥作用
<h4>Teachers</h4>
<div class="cust-detail" *ngFor="let teacher of teachers">
<tr>
<td>Name</td>
<td>{{ teacher.teacherName }}</td>
</tr>
<tr>
<td>Sessions</td>
<div *ngFor="let session of sessions">
<span *ngFor="let id of session.teacherId">
<span *ngIf="id == teacher.id">
<h2>{{ session.sessionName }}, {{ session.id }}</h2>
<p>{{session.notes}}</p>
</span>
</span>
</div>
</tr>
<hr>
</div>
在将其插入之前,请不要忘记从JSON中删除箭头。
答案 1 :(得分:1)
您需要像下面一样操作JSON
-
getManipulatedData() {
this.teachers && this.teachers.forEach(res => {
res['subjects'] = [];
this.sessions.forEach(obj => {
if (obj['teacherId'].includes(res.id)){
res['subjects'].push({subject: obj.sessionName, notes: obj.notes})
}
});
});
}
<h4>Teachers</h4>
<div class="cust-detail" *ngFor="let teacher of teachers">
<tr>
<td>Name</td>
<td>{{teacher.teacherName }}</td>
</tr>
<tr>
<td>Sessions</td>
<td><br>
<div *ngFor='let subject of teacher?.subjects'>
<h2>{{subject?.subject}}</h2>
<p>{{subject?.notes}}</p>
</div>
</td>
</tr>
<hr>
</div>
您还需要像这样在API调用端调用此方法-
ngOnInit() {
this.myService.getContacts()
.subscribe(res => {
this.teachers = res;
this.getManipulatedData();
});
this.myService.getWorkers()
.subscribe(res => {
this.sessions = res;
this.getManipulatedData();
});
}