I have an array users:
[0: {id:123, firstname:'xyz', lastname:'abc'}, 1:{id:456, firstname:'foo', lastname:'bar'}, 3:{id:567, firstname:'bar', lastname:'baz'}]
I have to loop through this array and call service API to get user appointments.
Method 1 which i feel is not best practice but solves issue
let userAppointments = []
for (let user of this.users) {
this._service
.getUsersAppointments(
{
date: this.todayDate,
id: user.id
},
this.token
)
.subscribe(res => {
// Modifying array as per requirements-----
userAppointments.push({
id: user.id,
name: `${user.firstname} ${user.lastname}`,
appointments: res
});
});
}
this.appointments = userAppointments
method 2: using forkJoin
Issue: I cannot access user firstname and last name when I finally get response from all calls. I need those details in my final array this.appointments i.e after calling subscribe where I am assigning res to this.appointments
forkJoin(
this.users
.map(res =>
this._service.getUsersAppointments(
{
date: this.todayDate,
id: res.id
},
this.token
)
)
.map(response => response)
).subscribe(res => {
// how can I access 'user object' keys like: firstname, id here--------------
this.appointments = res;
});
Please let me know if my problem is not clear.
Referred SO answer and codereview question for method 2