Angular - 如何为多个 http 请求实现 switchMap?

标签 angular rxjs angular-pipe angular12 switchmap

在我的项目中,有时我想在用户更改另一个列表中的选定值时更新列表中的可用选项。为此,我使用了 valueChangespipe运算符和 switchMap像这样:

this.form.controls.typeControl.valueChanges
  .pipe(
    switchMap((typeId: number) => {
      return this.typesService.getProjectsByType(typeId);
    }),
  )
  .subscribe((projects) => {
    //...
  });

现在我遇到了一个问题,我需要一次执行两个 http 请求来更新多个列表而不是一个。当我尝试添加第二个 switchMap , 我得到 error TS2345: Argument of type 'OperatorFunction<number, Project[]>' is not assignable to parameter of type 'OperatorFunction<any, number>'.这是我尝试这样做的方法:

this.form.controls.typeControl.valueChanges
  .pipe(
    switchMap((typeId: number) => {
      return this.typesService.getProjectsByType(typeId);
    }),
    switchMap((typeId: number) => {
      return this.typesService.getProgramsByType(typeId);
    }),
  )
  .subscribe(([projects, programs]) => {
    //...
  });

如何在此处添加第二个 http 请求,以便处理 subscribe 中两个请求收到的数据? ?

最佳答案

您可以使用 combineLataestforkJoin 创建一个可观察对象,当它的任一来源发出时发出:

this.form.controls.typeControl.valueChanges.pipe(
    switchMap(typeId => combineLatest([
      this.typesService.getProjectsByType(typeId),
      this.typesService.getProgramsByType(typeId)
    ]))
  )
  .subscribe(([projects, programs]) => {
    // ...
  });

但是,如果这两个数据(projectList 和 programList)彼此不相关,您可能会发现将它们定义为单独的可观察对象会更方便:

private typeId$ = this.form.controls.typeControl.valueChanges;

projectList$ = this.typeId$.pipe(switchMap(id => this.typesService.getProjectsByType(id)));
programList$ = this.typeId$.pipe(switchMap(id => this.typesService.getProgramsByType(id)));

这可以为您提供更精细的控制,并允许您更轻松地在模板中使用 async 管道:

    <h1> Projects </h1>
    <ul> 
        <li *ngFor="let project of projectList$ | async">
            {{ project.name }}
        </li>
    </ul>

    <h1> Programs </h1>
    <ul> 
        <li *ngFor="let program of programList$ | async">
            {{ program.name }}
        </li>
    </ul>

关于Angular - 如何为多个 http 请求实现 switchMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71708541/

相关文章:

javascript - ionic native /日期选择器 StaticInjectorError

rxjs - 每次其中一个发出 zip 2 observable

node.js - 无法安装 "@angular/cli"

Angular2 - 使用 POST 和 angular-in-memory-web-api

javascript - 了解 RxJS 去抖语义

javascript - RXJS:第一次拖动后捕获拖动事件不起作用

angular - 注入(inject)自定义管道进行单元测试

Angular 垫自动完成并突出显示管道问题

angular - 如何对 4 个元素使用 ngFor?

angular - 类型 'wakeLock' 上不存在属性 'Navigator'