I would use a subject to keep everything reactive. In your template html listen to change events and emit a new value to the subject.
<searchBar (change)="search$.next($event.target.value)" />
then in your component:
this.subscription = this.search$.pipe(
debounceTime(800),
distinctUntilChanged(),
switchMap(searchText=>http.post('api_link', {searchText})
}).subscribe(response=>{
this.response = response.
});
The switchMap will cancel any HTTP request that hasn’t completed if a new value is emitted through the subject. You can play with the debouneTime to see what feels right for you. Lastly, make sure you unsubscribe from your subject in the ngOnDestroy, this will prevent any memory links and keep everything nice and perfromant.:
ngOnDestroy(){
this.subscription.unsubscribe();
}
Suresh’s answer has a distinctUntilChanged()
which is an excellent addition to the solution. I’m adding it but want to give credit to his answer below. This is a benefit because if I search for egg
the request is made. But then I add an s
the end of egg and change my mind before the debounce is completed another duplicate HTTP post with a search of egg will not be made.