Angular RxJS 在第一次请求时合并多个依赖的 GET 请求 returns

Angular RxJS combine multiple dependant GET requests when first request returns

假设我有一个具有两个属性的 Student:courseIds、courses。

export interface IStudent {
  courseIds: number[];
  courses: ICourse[];
}

export interface ICourse {
  name: string;
}

当页面加载时,我发出 GET 请求以检索仅填充 courseId 的 Student。然后我想验证这些 ID,并向不同的端点发出未知数量的附加 GET 请求以检索他的课程。
最后,我想要一个包含填充 Courses 数组的 Student 对象。

我走到这一步:

httpClient.get<IStudent>(url)
  .pipe(
    map(student => {
      const validIds = [];
      student.courseIds.forEach(id => {
        if (isValid(id)) {
          validIds.push(id);
        }
      }
      return validIds;
    }),
    ???
  ).subscribe(
    ???
  );

问号表示卡住的地方。我如何使用 Observables 来实现它?

在您的管道中,您可以 map 并在使用 switchMapforkJoin 获取 ICourse 数组之前过滤您的有效 ID。

httpClient.get<IStudent>(url)
  .pipe(
    map(student => student.courseIds.filter((id: number) => isValid(id))),
    switchMap((ids: number[]) => forkJoin(ids.map(id => httpClient.get<ICourse>(id))))
  )
  .subscribe({
    next: (data: ICourse[]) => {
      /* use your course array */
      console.log(data)
    },
    error: (error) => console.log(error),
  }
);

您可能希望将 http 服务 class 拆分,这样您就可以干净地 'gets' 并在组件服务 class 中进行拼接。那么你只需要在组件中订阅或者使用异步管道即可。

StackBlitz Example