簡體   English   中英

角度5-另一個觀察者內部的觀察者循環-做到這一點的有效方法

[英]angular 5 - loop of observers inside an other observer - efficient way to do it

我有一個“獲取”調用,該調用返回包含用戶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>

其中顯示圖片是僅顯示圖像的組件。

有沒有使用rxjs的有效方法呢?

from開始迭代每個用戶,並可以在此處使用mergeScan執行可觀察對象。 為了清楚起見,我將其分為兩個功能。 您還可以使用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

您可以使用forkJoin()將來自多個可觀察對象的所有最終發出的值合並在一起。 RxJS 6支持使用鍵/值對的對象映射來定義哪些可觀察對象,但是對於較舊的版本,必須使用數組。

this.dashboardService.bringUsers().pipe(
   switchMap(users => forkJoin(
       users.reduce((acc, user) => (acc[user.userId] = this.dashboardService.getPicture(user.userID), acc), {}
   ))),
).subscribe((users: {[userId: number]: any}) => {
   Object.entries(users).forEach(([userId, data]:[number,any]) => {
      this.userPhotos[user.userID] = data ? window.URL.createObjectURL(data) : '';
   });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM