调用多个 http 并返回多个 observables

问题描述 投票:0回答:1

我正在尝试调用多个 http 并将多个 observables 合并为一个,但始终只发出最后一个。 我有带 formcontrol ctl 的输入字段,当输入关键字时,搜索客户、项目和任务。

    ctl: FormControl = new FormControl();

    this.list$ = this.ctl.valueChanges
      .pipe(
        debounceTime(100),
        startWith(null),
        mergeMap((res: any) => {
          if (res) {
            this.keyword = res;
            return forkJoin([this.dataService.searchCustomer(res),
                             this.dataService.searchItem(res),
                             this.dataService.searchTask(res)]);
          } else {
            return of([]);
          }    
        })
      );

我试过了

<input  type="text" placeholder="Enter title" aria-label="Number" matInput [formControl]="ctl"
             [matAutocomplete]="auto" >
      <mat-autocomplete #auto="matAutocomplete">
          <ng-container *ngFor="let list of list$ | async ; let i = index">
            <mat-option *ngFor="let option of list | async" >
              {{option.id}}
            </mat-option>
          </ng-container>
      </mat-autocomplete>

但是我收到错误您在需要流的地方提供了“未定义”。您可以提供 Observable、Promise、ReadableStream、Array、AsyncIterable 或 Iterable。

如何返回多个可观察对象并订阅显示?

angular rxjs observable
1个回答
0
投票
  1. forkJoin
    之后,使用
    map
    运算符将每个可观察对象的数组组合成单个数组。
import {
  debounceTime,
  forkJoin,
  map,
  Observable,
  of,
  startWith,
  mergeMap,
} from 'rxjs';

this.list$ = this.ctl.valueChanges.pipe(
  debounceTime(100),
  startWith(null),
  mergeMap((res: any) => {
    if (res) {
      this.keyword = res;
      return forkJoin([
        this.dataService.searchCustomer(res),
        this.dataService.searchItem(res),
        this.dataService.searchTask(res),
      ]).pipe(map(([a, ...b]) => a.concat(...b)));
    } else {
      return of([]);
    }
  })
);
  1. 修改视图部分以渲染
    option
    observable 中的每个
    list$
    对象。
<mat-autocomplete #auto="matAutocomplete">
  <ng-container *ngFor="let option of list$ | async ; let i = index">
    <mat-option>
      {{option.id}}
    </mat-option>
  </ng-container>
</mat-autocomplete>

Demo @ StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.