首页 > 解决方案 > 角度 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 的有效方法来做到这一点?

标签: javascriptangulartypescriptrxjsrxjs6

解决方案


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)

https://stackblitz.com/edit/rxjs-1bt172


推荐阅读