【问题标题】:Angular - Forkjoin after forkjoinAngular - 分叉后的分叉
【发布时间】:2021-05-30 21:28:51
【问题描述】:

您好,我最近刚刚发现了 forkjoins 对 API 的强大功能,并尝试使用它来加快加载时间。正如标题所说,寻求关于在 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??****//
 }
);

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

【问题讨论】:

    标签: angular rxjs6 fork-join


    【解决方案1】:

    你快到了。使用像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
      }
    });
    

    HereforkJoin 运算符和 switchMap 函数的简要比较。

    【讨论】:

    • 非常感谢您的帮助。关于错误捕获,这是否意味着如果任何 API 失败,它将立即被错误捕获:?并且所有其他 API 响应都将被忽略(首选)
    • @KaTech:是的,如果任何源 observable 发生错误,所有 observable 都将关闭,并向订阅发送错误。尽管您需要注意,由于所有可观察对象都是并行触发的,因此可能会发生其中一个源在错误之前完成,但是不会发出此值,只会发出错误。
    • 太棒了我已经开始实施我已经看到我的页面加载时间减少了一半。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2013-04-28
    • 2011-08-10
    • 2012-08-05
    • 2020-01-29
    • 2017-03-15
    • 2015-12-12
    相关资源
    最近更新 更多