Создайте Observable из события и затем примените debounceTime
оператор
import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
//create observable that emits 'place_changed' events
const source = fromEvent(autocomplete, 'place_changed');
//map to string with given event timestamp
const example = source.pipe(debounceTime(4000));
const subscribe = example.subscribe(val => console.log(val));
Кстати, 4-5 сек - это слишком много.Время отката - это время после последнего нажатия клавиши.
UPDATE # 1
Попробуйте добавить следующую директиву в поле ввода, где пользователь вводит свой запрос
debounce-time.directive.ts
import {AfterViewInit, Directive, ElementRef, forwardRef, Input, OnDestroy, Renderer2} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {fromEvent, Subject} from 'rxjs';
import {debounceTime, takeUntil} from 'rxjs/operators';
// tslint:disable:directive-selector
@Directive({
selector: '[debounceTime]',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DebounceTimeDirective),
multi: true
}]
})
export class DebounceTimeDirective extends Destroyable implements ControlValueAccessor, AfterViewInit, OnDestroy {
protected destroyed$ = new Subject<boolean>();
@Input()
debounceTime: number;
onChange = (_) => {};
onTouched = () => {};
constructor(private _elementRef: ElementRef, private renderer: Renderer2) {
super();
}
ngAfterViewInit() {
fromEvent(this._elementRef.nativeElement, 'keyup')
.pipe(
takeUntil(this.destroyed$),
debounceTime(this.debounceTime)
)
.subscribe((event: any) => {
this.onChange(event.target.value);
});
}
ngOnDestroy(): void {
this.destroyed$.next(true);
this.destroyed$.complete();
}
writeValue(value: any): void {
const normalizedValue = value === null || value === undefined ? '' : value;
this.renderer.setProperty(this._elementRef.nativeElement, 'value', normalizedValue);
}
registerOnChange(fn: () => any): void { this.onChange = fn; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
}
your-template.html
<input [debounceTime]="4000" ... />