【问题标题】:RxJs: merge stream data and a promiseRxJs:合并流数据和承诺
【发布时间】:2022-12-07 08:01:08
【问题描述】:

我想显示用户的数据和他们的个人资料图片。但是我从两种不同的服务中获得了基本数据和个人资料图片。我想做的是将图片的 url 合并到我的 tableData 中。

到目前为止我的代码:

interface User {
  id: number,
  name: string,
  email: string
}

interface UserWithPicture extends User {
  image: string[] | "",
}

interface ProfileImage {
  id: number,
  url: string
}

  tableData: UserWithPicture[];
  profileImage: ProfileImage[];

两个异步函数都返回对象数组。


async ngOnInit() {
  this.tableData = await this.getUserDataService.fetchUsers().toPromise();
  const userID = this.tableData.map(u => u.userId);

  from(this.userProfilService.getUserProfileImage(userID))
    .pipe(takeUntil(this.destroy$),
      map(userProfileImages => userProfileImages.filter(user => user.id).map(upi => upi.url)))
    .subscribe(data => {
        this.userProfileImage = data;
      }
    })
}

我试图将 url 添加到表数据中,但我不能在相关代码块之外这样做,它总是会返回未定义的。

const newArr = this.tableData.map(v => Object.assign(v, {image: this.userProfileImage}))

如何将 this.userProfileImage 合并到数组的 tableData 对象中?

【问题讨论】:

    标签: javascript typescript rxjs


    【解决方案1】:

    您可以使用 switchMap rxjs 运算符将 this.userProfileImage 合并到数组的 tableData 对象中。 在“组合系列中的 Observables”一节中,这里有一个很好的例子来说明这个场景: https://blog.danieleghidoli.it/2016/10/22/http-rxjs-observables-angular/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      相关资源
      最近更新 更多