I am trying to write a code where an Angular Course Service receives the login id of a student to list all courses where the student enrolls. This result is then piped to another service which takes the output of the first query as its input.
teachers: ITeacher[];
this.courseService.query({
'stdId.equals': this.account?.login,
}).pipe(
map(data=> {
this.teacherService.query({
'courseId.in': data.body,
}).subscribe((res: HttpResponse<ITeacher[]>) => {
this.teachers = res.body;
})
})
);
The problem is that I am able to see the results in data.body, but I cannot get the actual values of the data. Eg. If I try to get the values as data.body.id, I get an error message saying there is no field id in the Class or Interface. I am new to Angular so these are my questions:
Any help is much appreciated.
I strongly suggest that you use an Observable as your final "target". Instead of having teachers as a static array, you would have teachers$, an Observable, which you would consume in the DOM with the async pipe or elsewhere in your code. Also, you want to avoid subscribing to Observables inside Observable pipes (nested subscribe calls are BAD code smell).
Here is my suggested approach:
teachers$: Observable<ITeacher[]>;
this.teachers$ = this.courseService.query({
'stdId.equals': this.account?.login,
}).pipe(
switchMap(data => this.teacherService.query({
'courseId.in': data.body,
}))
);
When you need to subscribe to a child Observable from inside a parent Observable (like in this case), you should use a higher-order mapping operator like switchMap, concatMap, mergeMap or exhaustMap. These operators differ mostly in their concurrency models. For this case, depending on how many requests could potentially be made, you may want to change from switchMap to something else.
Embracing the suggestion from this answer, I'd just add the solution to the array of course ids as follows:
teachers$: Observable<ITeacher[]>;
this.teachers$ = this.courseService.query({
'stdId.equals': this.account?.login,
}).pipe(
map(data => data.body.map(({id}) => id)),
map(data => this.teacherService.query({
'courseId.in': data,
}))
);
I didn't test it but I think you can try this.