我有两个名为teachers
和sessions
的JSON文件,如下所示:
老师
[
{
"name": "Teacher 1",
"sessionId": "02"
},
{
"name": "Teacher 2",
"sessionId": "03"
},
{
"name": "Teacher 3",
"sessionId": "01"
}
]
会话
[
{
"id":"01",
"name": "Session 01"
},
{
"id":"02",
"name": "Session 02"
},
{
"id":"03",
"name": "Session 03"
},
{
"id":"004",
"name": "Session 04"
}
]
我想像这样显示特定teacher
的会话:
但是我不能,下面是我的组件代码:
HTML
<h4>Teachers</h4>
<div class="cust-detail" *ngFor="let teacher of teachers">
<tr>
<td>Name</td>
<td>{{teacher.name }}</td>
</tr>
<tr>
<td>Assigned Session: </td>
<li *ngFor="let session of selectedSession">{{session?.name}}</li>
</tr>
<hr>
</div>
TS
import { Component } from '@angular/core';
import { ContactService } from './contacts.service';
import{ ISessions,ITeachers} from '../models/app.models';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
teachers: ITeachers[];
sessions: ISessions[];
public selectedSession: ISessions[];
constructor(private myService: ContactService) {}
ngOnInit() {
this.myService.getTeachers()
.subscribe(res => this.teachers = res);
this.myService.getSession()
.subscribe(res => this.sessions = res);
for (const teacher of this.teachers) {
if (teacher.sessionId) {
this.getSessionById(teacher.sessionId);
}
}
}
public getSessionById(sessionId: string){
this.selectedSession = this.sessions ? this.sessions.filter((x: ISessions) => x.id === sessionId) : [];
console.log(this.selectedSession);
}
}
答案 0 :(得分:2)
您可以处理以下结果:
this.result = this.teachers.map(teacher =>
({...this.sessions.find(p => teacher.sessionId === p.id), teacher}));
演示https://stackblitz.com/edit/angular-join-object
已更新:
我将查询更新为小组老师和他们教的课,可能是一位老师教了很多课。
this.result = this.teachers.map(teacher =>
({session: this.sessions.filter(p => teacher.sessionId === p.id), teacher}));
答案 1 :(得分:1)
您绝不应在订阅中进行订阅。最好使用zip,forkJoin或类似名称。然后,您可以减少数据并按需要进行分组
zip(this.myService.getTeachers(), this.myService.getSession())
.pipe(
flatMap(([t, s]) => {
return of(t.reduce((a, b) => {
a[b.sessionId] = (a[b.sessionId] || b);
a[b.sessionId].sessions = s.filter(e => e.id === b.sessionId);
return a;
}, {}));
})
).subscribe(e => this.teachers = e);