【问题标题】:Angular RxJS combine multiple dependant GET requests when first request returns当第一个请求返回时,Angular RxJS 组合多个依赖的 GET 请求
【发布时间】:2023-03-31 17:40:01
【问题描述】:

假设我有一个具有两个属性的学生:courseIds、课程。

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

export interface ICourse {
  name: string;
}

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

我已经走到这一步了:

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

问号表示我被困在哪里。如何使用 Observables 实现这一点?

【问题讨论】:

    标签: angular rxjs observable ngrx angular-httpclient


    【解决方案1】:

    在您的管道中,您可以在使用 switchMapforkJoin 之前过滤您的有效 id 以获取一系列 ICourse。

    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 服务类,以便拥有干净的“gets”并在组件服务类中进行拼接。然后你只需要订阅或使用组件中的异步管道。

    StackBlitz Example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2021-04-22
      相关资源
      最近更新 更多