If I use in a component a ngx-typeahead
directive as below
<input type="search"
[(ngModel)]="asyncSelected"
[typeahead]="dataSource"
(typeaheadLoading)="changeTypeaheadLoading($event)"
(typeaheadNoResults)="changeTypeaheadNoResults($event)"
(typeaheadOnSelect)="typeaheadOnSelect($event)"
[typeaheadWaitMs]="200"
[typeaheadMinLength]="2"
[typeaheadOptionsInScrollableView]="10"
[typeaheadSingleWords]="false"
[typeaheadScrollable]="true"
[typeaheadItemTemplate]="someTemplate"
/>
With dataSource
initiated in the component's constructor :
this.dataSource = Observable.create((observer: any) => {
observer.next(this.asyncSelected);
}).mergeMap((token: string) => {
return this.http.post<DevisResponses>('http://example.com/api',token);
});
When I'm writing in the <input/>
some letters a request A will be made 200Ms later, but if I'm then quickly enter another letter before the end of the call then I'll have a new request B with results mixed with the one from request A !
It seems that [typeaheadWaitMs]
is the only parameter available to prevent a request, but could I abort a previously made and unfinished request ?
So, as @Daniel B and @Alexander Poshtaruk pointed in their comments, I had to import the swithMap
operator and use it instead of mergeMap
because, as stated in the doc :
When a new inner Observable is emitted, switchMap stops emitting items from the earlier-emitted inner Observable and begins emitting items from the new one.
So after import { switchMap } from 'rxjs/operators';
here's how I initiate dataSource
now:
this.dataSource = Observable.create((observer: any) => {
observer.next(this.asyncSelected);
}).mergeMap((token: string) => {
return this.http.post<DevisResponses>('http://example.com/api',token);
});
But still, I don't understand why can't I use .switchMap
as a method of the created Observable
(as written in the doc example)