Angular-Material-Autocomplete icon indicating copy to clipboard operation
Angular-Material-Autocomplete copied to clipboard

How to make service.fetch(params) not to fire at every keystroke?

Open hamdyl052 opened this issue 5 years ago • 1 comments

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

hamdyl052 avatar Dec 04 '19 05:12 hamdyl052

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); });

jonesy827 avatar Dec 17 '19 22:12 jonesy827