我用的是 ng-select 自定义服务器端搜索,根据用户输入的内容加载数据。目前,只有当一个关键字被实际按下时,它才会工作。
<ng-select [items]="filterValues$ | async"
[typeahead]="filterValuesInput$"
[multiple]="true"
(open)="getFilterValues(pref.id)"
[loading]="filterValuesLoading"
bindLabel="name"
[(ngModel)]="filter_values">
</ng-select>
我想在选择下拉打开时触发API请求。甚至 如果没有提供搜索词。
getFilterValues(filterId) {
this.filterValues$ = concat(
of([]), // default items
this.filterValuesInput$.pipe(
distinctUntilChanged(),
tap(() => this.filterValuesLoading = true),
switchMap(term => this.service.getFilterValues(filterName, '' + term).pipe(
map(res => res.filter_values),
catchError(() => of([])), // empty list on error
tap(() => this.filterValuesLoading = false)
))
)
);
}
有什么建议吗?
发生这种情况的原因是由于第二个观测值的原因,concat没有发出任何值。你可以尝试使用startWith操作符进行初始加载
getFilterValues(filterId) {
this.filterValues$ = concat(
of([]), // default items
this.filterValuesInput$.pipe(
startWith(''),
debounce(300),
distinctUntilChanged(),
tap(() => this.filterValuesLoading = true),
switchMap(term => this.service.getFilterValues(filterName, '' + term).pipe(
map(res => res.filter_values),
catchError(() => of([])), // empty list on error
tap(() => this.filterValuesLoading = false)
))
)
);
}
希望能帮到你