Angular - forkjoin 后的 Forkjoin

问题描述

嗨,我最近发现了 API 的 forkjoins 的强大功能,并尝试使用它来加快加载时间。正如标题所说,寻求有关在 forkjoin 之后运行 forkjoin 的最佳实践的帮助。

我有一个 forkjoin,它可以为 2 个 API 获取一些数据。根据抓取的数据,我需要为额外的 2 个 API 运行第二个 forkjoin。

在给定 id 的第一个 forkjoin 中,我获取表单数据和 UX 样式数据。

const form = this.apiService.getForm(id);
const style = this.apiService.getFormStructure(id);

在第二个 forkjoin 中,我想将表单数据中找到的 photoIds 传递给 2 x APIS:

this.apiService.getPhotoUrls(photoIds)
this.apiService.getPhotoHistory(photoIds)

这是我目前所拥有的:

let formId: string = '1';
const form = this.apiService.getForm(id);
const style = this.apiService.getFormStructure(id);


forkJoin([form,style])
.subscribe(
 (data:Object[]) => {
   // handle result
   let formData = data[1];
   let formStyle = data[2];
   let photoIds:number[] = formData.photoIds;
   //***What is the best to pass the photo Ids to run the next 2 APIS??****//
 }
);

非常感谢您提前提供帮助!

解决方法

你快到了。使用像 switchMap 这样的高阶映射运算符从一个可观察对象切换到另一个。您还可以使用解构赋值跳过明确的 formDataformStyle 初始化

forkJoin([form,style]).pipe(
  switchMap(([formData,formStyle]) => {
      let photoIds: number[] = formData['photoIds'];
      return forkJoin([
        this.apiService.getPhotoUrls(photoIds)
        this.apiService.getPhotoHistory(photoIds)
      ]);
  })
).subscribe({
  next: ([urls,history]) => {
    // `urls` - response from `apiService.getPhotoUrls(photoIds)`
    // `history` - response from `apiService.getPhotoHistory(photoIds)`
  },error: (error: any) => {
    // handle error
  }
});

Here 是 b/n forkJoin 运算符和 switchMap 函数的简要比较。