【发布时间】:2019-04-08 18:41:40
【问题描述】:
我有一个数组用户:
[0: {id:123, firstname:'xyz', lastname:'abc'}, 1:{id:456, firstname:'foo', lastname:'bar'}, 3:{id:567, firstname:'bar', lastname:'baz'}]
我必须遍历这个数组并调用服务 API 来获取用户约会。
方法 1 我觉得这不是最佳实践,但可以解决问题
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
方法2:使用forkJoin
问题:当我最终得到所有呼叫的响应时,我无法访问用户的名字和姓氏。我在我的最终数组 this.appointments 中需要这些详细信息,即在调用 subscribe 我分配 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;
});
如果我的问题不清楚,请告诉我。
引用 SO answer 和 codereview question 用于方法 2
【问题讨论】:
标签: angular angular7 angular-observable