我正在尝试调用多个 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。
如何返回多个可观察对象并订阅显示?
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([]);
}
})
);
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>