javascript - 角度 5 - 另一个观察者内部的观察者循环 - 有效的方法
问题描述
我有一个“get”调用,它返回一个包含用户 ID 和名称的用户列表。调用成功后,我需要为每个用户调用另一个休息来带他的照片。
目前我正在这样做 -
零件-
users;
userPhotos = {};
constructor(private dashboardService: DashboardService) {
this.dashboardService.bringUsers().subscribe((data) =>{
this.users = data;
this.users.forEach((user) => {
this.dashboardService.getPicture(user.userID).subscribe((data) => {
if (data){
this.userPhotos[user.userID] = window.URL.createObjectURL(data);
} else {
this.userPhotos[user.userID] = '';
}
});
});
});
}
在我的 html-
<ng-container *ngFor="let user of users">
<div>
{{user.displayName}}
</div>
<display-picture [image]="userPhotos[user.userID]"></display-picture>
</ng-container>
其中 display-picture 是仅呈现图像的组件。
有没有使用 rxjs 的有效方法来做到这一点?
解决方案
from
迭代每个用户,并mergeScan
可以在此处用于执行可观察对象。为清楚起见,我将其分为两个功能。您还可以控制并发数mergeScan
const getUserPic=users=>from(users).pipe(
mergeScan((acc, curr:any) =>
getPicture(curr.userID).pipe(map(photo => {
acc[curr.userID] = photo
return acc
}))
,{})
)
bringUsers().pipe(
tap(users=>this.users=users),
switchMap(users=> getUserPic(users)),
last()
).subscribe(console.log)
推荐阅读
- ios - Unity/Videoplayer - 如果我加载下一个视频,游戏有时会崩溃
- azure - 入口得到 502 错误网关
- php - Discord oAuth2 API ratelimit 在没有任何(已知)原因的情况下触发
- reactjs - 子组件更新 HOC 父状态后获取子组件新的 HOC 状态
- objective-c - 为什么在 Objective-C 中将指针 * 用于字符串而不用于整数
- flutter - Flutter 如何获取imei
- amazon-web-services - AWS ALEXA 无法看到“发送 Alexa 事件”滑块
- typescript - 在静态方法中使用类类型
- php - 在 WordPress 帖子中插入随机变量
- c - C中的结构内部结构(链表)