ngx-bootstrap typeahead observable

Viewed 2907

So I have a a typeahead input field that looks like this:

<input formControlName="segment"
              [typeahead]="segments"
              (typeaheadLoading)="segmentsLoading($event)"
              (typeaheadNoResults)="segmentsNoResults($event)"
              (typeaheadOnSelect)="segmentOnSelect($event)"
              typeaheadOptionsLimit="10"
              typeaheadMinLength="3"
              typeaheadWaitMs="300"
              [typeaheadItemTemplate]="customSegmentTemplate"
              class="form-control">

And an Observable which helps me get the suggestions in typeahead.

this.segments = Observable.create((observer: any) => observer.next(this.segments))
  .mergeMap((number: string) => this.suggestionsService.getSegmentSuggestions(this.editForm.get('segment').value);

My problem is that the Observable sends a request even when my input field value length is less than 3 even if I have set typeaheadMinLength="3". This happens when user types in a value and then deletes some of the characters quickly (quicker than my debounce time) and then tries to enter a new value. My API for suggestions fails when it recieves input value with length less than 3 and then my application breaks and I have to refresh the page to make it work again. I have tried to set debounce time to 0 and I didnt have this issue then, but that is a bad practice and it sends too many requests to my API. Any ideas on how to solve this?

2 Answers

Here's a sketch of a work around that could help until they fix the control:

Pipe a filter operator before your observable fires the service call:

this.segments = Observable.create((observer: any) => observer.next(this.segments))
    .pipe(filter(number => number.length >= YOUR_MIN_LENTH_LIMIT),
    .mergeMap((number: string) => this.suggestionsService.getSegmentSuggestions(this.editForm.get('segment').value));
Related