我需要[options]
动态填充我的数组,一旦用户完成输入,我需要进行 API 调用并获取我的选项列表。
为了避免多次 API 调用,我想使用类似 rxjsdebounceTime(1000);
有没有办法使用 debounceTime?或者还有其他推荐的选项可以使用吗?
我需要[options]
动态填充我的数组,一旦用户完成输入,我需要进行 API 调用并获取我的选项列表。
为了避免多次 API 调用,我想使用类似 rxjsdebounceTime(1000);
有没有办法使用 debounceTime?或者还有其他推荐的选项可以使用吗?
您可以使用缓冲区和 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 ));
就像 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>