I have two models;
export interface Student {
id: string,
name: string
}
export interface StudentGoal{
id: string,
studentId: string,
goal: string
}
I get the students in my StudentService like this:
getStudents(): Observable<Student[]> {
return this.http.get<Student[]>("URL_1");
}
I get a student goal like this:
getStudentGoal(studendId: string): Observable<StudentGoal> {
return this.http.get<StudenGoal>("URL_2" + studentId);
}
QUESTION
What is the best practice to get student goal inside *ngFor in my student.goal.component
.ts
private subs = new SubSink()
public students: Student[] = [];
constructor(
private studentService: StudentService
)
ngOnInit() {
this.getStudents();
}
ngOnDestroy() {
this.subs.unsubscribe()
}
getStudents(){
this.subs.sink = this.studentService.getStudents().subscribe((res: Student[]) => {
this.students = res
})
}
getStudentGoal(studentId: number){
BEST PRACTICE ?
}
.html
<div *ngFor="let student of students">
{{getStudentGoal(student.id).goal}}
</div>
1.- When we mannage Observables we have two differents things: the "response" and the "subscription"
this.subscription is a subscription and only is util when we want unsubscribe. it's NOT the response
2.-When we use in .html observables we can
show a variable that we are using inside subscribe function
use async pipe
but not {{subscription}}
3.-When we mannage a ngFor subscription sometimes is util read all we need. For this we use switchmap and forkJoin
So we can use