在 switchMap 中进行嵌套的 Http 调用

Make nested Http calls inside switchMap

if (this.role === 'admin' || this.role === 'superadmin') {
  this.organizationService.getDropdownOrganizations().pipe(
    tap(availableOrganizations => {
      this.availableOrganizations = availableOrganizations;
    }),
    switchMap(availableOrganizations => {
      return this.projectService.getProjects(availableOrganizations[0]?.id);
    }),
  ).subscribe(availableProjects => {
    this.availableProjects = availableProjects;
    this.getNotifications();
  });
} else {
  this.getNotifications();
}

大家好,

在上面的代码中,我将 orgId 传递给项目服务并订阅 availableProjects

我的问题是我想向 getUsers() 发出另一个与 getProjects() 相同的请求并传递 orgId 并通过此获取项目和用户。

如何做到?

如果您希望它们同时执行,我会使用 forkJoin 来做到这一点。

switchMap(availableOrganizations => {
  return forkJoin([
      this.projectService.getProjects(availableOrganizations[0]?.id),
      this.projectService.getUsers(availableOrganizations[0]?.id);
  ]);
}),

然后您可以访问这两个值作为传递给下一个流运算符的数组的属性。我建议在那里使用数组解构:

).subscribe(([availableProjects, users ]) => {

您可以订阅同一个 cold observable 并将结果分享给 shareReplay

if (this.role === 'admin' || this.role === 'superadmin') {
  const availableOrganizations$ = this.organizationService.getDropdownOrganizations().pipe(
    shareReplay(1),
  );

  availableOrganizations$.subscribe(availableOrganizations => this.availableOrganizations = availableOrganizations);

  availableOrganizations$.pipe(
    switchMap(availableOrganizations => this.projectService.getProjects(availableOrganizations[0]?.id)),
  ).subscribe(availableProjects => {
    this.availableProjects = availableProjects;
    this.getNotifications();
  });

  // TODO: same for user as the previous block
} else {
  this.getNotifications();
}

还有很多我们不知道的。我假设 getProjectsgetUsers 都发出一次然后完成。如果是这种情况,您可以使用 forkJoin 一次处理两者,并在完成后 return 两者的结果。

可能看起来像:

if (this.role === 'admin' || this.role === 'superadmin') {
  this.organizationService.getDropdownOrganizations().pipe(
    tap(availableOrganizations => 
      this.availableOrganizations = availableOrganizations
    ),
    switchMap(availableOrganizations => forkJoin({
      projects: this.projectService.getProjects(availableOrganizations[0]?.id),
      users: this.projectService.getUsers(availableOrganizations[0]?.id)
    })),
  ).subscribe(({projects, users}) => {
    this.availableProjects = projects;
    this.availableUsers = users;
    this.getNotifications();
  });
} else {
  this.getNotifications();
}