Har*_*mer 3 angular angular-observable angular7
我有一个数组用户:
[0: {id:123, firstname:'xyz', lastname:'abc'}, 1:{id:456, firstname:'foo', lastname:'bar'}, 3:{id:567, firstname:'bar', lastname:'baz'}]
Run Code Online (Sandbox Code Playgroud)
我必须循环遍历此数组并调用服务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
Run Code Online (Sandbox Code Playgroud)
方法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;
});
Run Code Online (Sandbox Code Playgroud)
如果我的问题不明确,请告诉我.
小智 6
当所有Observable传入它时,forkJoin只发出一次.它发出一个Array,其元素是每个Observable在完成之前发出的值的结果.发出的数组的一个关键特性是元素序列与构造forkJoin时传递的Observable序列相同(类似于Promise.all()).这可以很好地解决您手头的问题.您可以迭代forkJoin的结果,并为每个索引从users Array中选择相应的元素,并将用户属性分配给结果对象.虽然这可以直接在上面的方法2中的订阅调用中完成.更好的解决方案是将此代码移动到使用Observable.create方法创建的新Observable中.这将阻止您在订阅forkJoin(ed)Observable的任何地方编写迭代逻辑.我在这里的stackblitz 演示中重新创建了相同的场景.检查控制台是否有所需的输出.
| 归档时间: |
|
| 查看次数: |
669 次 |
| 最近记录: |