【问题标题】:Angular2+ - Combining 2 observables calls into oneAngular2+ - 将 2 个 observables 调用合二为一
【发布时间】:2022-01-09 09:51:58
【问题描述】:

我正在尝试将这两个调用合并为一个,以便它们调用异步或随后调用。我在想我必须使用 map 或 switchMap。

imageType 是一个枚举。

它应该以字符串 uri 的形式返回。

枚举

export enum ImageType {
    Avatar = 1,
    Cover = 2
}

组件.ts

this.service.getphotos(ImageType.Avatar, this.id).subscribe(result => {
    this.avatarPhotos = result;
});

this.service.getphotos(ImageType.Cover, this.id).subscribe(result => {
    this.coverPhotos = result;
});

service.ts

getPhotos(imageType: ImageType, id: number): Observable<string[]> {
    return this.http.get<string[]>(`api/getphotos/${imageType}/${id}`);
    }

【问题讨论】:

  • 你可以使用combineLatest
  • 如果其中一个调用失败,答案会有所不同,具体取决于您希望发生的情况。预期的行为是什么?
  • 我没想到。目前,如果图像不可用,那么我有一个默认图像,它在 上实现 onError。如果一个调用失败,那么我希望它出错(为了便于阅读,我删除了错误)。
  • 谢谢,我会查一下 combineLatest

标签: angular typescript rxjs observable


【解决方案1】:

简单的解决方案,在这里:

combineLatest([
  this.service.getphotos(ImageType.Avatar, this.id).pipe(
    tap(result => (this.avatarPhotos = result)),
  ),
  this.service.getphotos(ImageType.Cover, this.id).pipe(
    tap(result => (this.coverPhotos = result)),
  )
]).subscribe()

您也可以使用forkJoin 执行此操作。

【讨论】:

  • 我认为应该是 'tap(result=> (this.avatarPhotos = result))',如果是,请编辑。我已将其标记为正确答案。谢谢您的帮助。我今天要花在 RxJs 上!
  • @Robgit28 好的,谢谢!
  • 实际上在示例中这不是好的做法,只有当属性不在模板中时。如果它在模板中, - 只需使用 async 管道。
猜你喜欢
  • 2019-09-11
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多