Angular-Material-Autocomplete
Angular-Material-Autocomplete copied to clipboard
How to make service.fetch(params) not to fire at every keystroke?
From the documentation: "If source is a service, on every key press component will call a service.fetch(params) method..."
How can I write the service.fetch(params) in such a way that it won't fire (call API) at every keystroke but instead wait for a break, e.g. every 500 ms, then fire? Calling a remote API at every keystroke is very expensive. I like to emulate the RxJS debounceTime, distinctUntilChanged, switchMap operators in an observable. The function fetch is based on Promise. I tried to use RxJS toPromise() but not working as I don't know how to set it up and how it's related to subscribe(). Thanks
To accomplish this, simply remove the (keyup)="onKey($event)"
from both inputs in autocomplete.component.html and place the following in ngAfterViewInit() method of that component:
fromEvent(this.autocompleteInput.nativeElement, 'keyup').pipe(debounceTime(500)).subscribe((value: KeyboardEvent) => { this.onKey(value); });