【发布时间】:2020-05-06 06:35:38
【问题描述】:
我需要动态填充我的[options] 数组,一旦用户完成输入,我需要进行 API 调用并获取我的选项列表。
为了避免多次 API 调用,我想使用类似 rxjs debounceTime(1000);
有什么方法可以使用 debounceTime 吗?或者还有其他推荐的选项吗?
【问题讨论】:
标签: rxjs angular6 ngx-select-dropdown
我需要动态填充我的[options] 数组,一旦用户完成输入,我需要进行 API 调用并获取我的选项列表。
为了避免多次 API 调用,我想使用类似 rxjs debounceTime(1000);
有什么方法可以使用 debounceTime 吗?或者还有其他推荐的选项吗?
【问题讨论】:
标签: rxjs angular6 ngx-select-dropdown
就像 Navruzbek 提到的,“ngx-mat-select-search”可用于服务器端下拉搜索。
但是,如果您想使用当前库并向其添加 debounceTime,则可以使用 Subject 来解决此问题。喜欢https://stackoverflow.com/a/39960980/7763714的建议
对我有用的解决方案:
searchTextChanged=new Subject<string>();
// make the server-side call in the subscrivbe function
ngOnInit() {
this.searchTextChanged.pipe( debounceTime(1000), distinctUntilChanged()) .subscribe((value)=> this.outerValuedChanged(value));
}
addressSearchChanged(searchText: string) {
if (searchText.length >=3) {
this.searchTextChanged.next(searchText);
}
}
// dummy function
outerValuedChanged(value: string) {
console.log('value:', value);
return 'test';
}
<ngx-select-dropdown (searchChange)="addressSearchChanged($event)" formControlName="inputAddressFormControl" [multiple]="false" [config]="config" [options]="addressList"></ngx-select-dropdown>
【讨论】:
您可以使用缓冲区和 api 调用而不是 ajax 来使用此技巧
import { fromEvent, timer } from 'rxjs';
import { debounceTime, map, buffer, switchMap } from 'rxjs/operators';
let input = document.getElementById('example');
let input$ = fromEvent(input, 'keyup');
let breakWhen$ = timer(1000);
let debounceBreak$ = input$.pipe(
debounceTime( 2000 )
);
let stream$ = input$.pipe(
map( ev => ev.key),
buffer(debounceBreak$),
switchMap((allTypedKeys) => {
// do ajax
console.log('Everything that happened during 2 sec', allTypedKeys)
return of('ajax based on ' + input.value);
});
);
stream$.subscribe((data) => console.log( 'values',data ));
【讨论】: