Angular2/4 – Switchmap keeps triggering more and more requests on every subsequent search

Home / Uncategorized / Angular2/4 – Switchmap keeps triggering more and more requests on every subsequent search

Question:
I’ve got an issue with (presumably) switchmap function used for my live search.

EDIT: My input looks like this:

There is a function getting triggered by an input which uses a service to make https request to the server.
searchPartnerByName(event) {
if ( event.length < 3 ) {return; } this.partnersParams.searchText = event; this.searchTermPartner.next(event); this.loadingService.changeBool(true); this.partnersService.search(this.searchTermPartner, this.partnersParams).subscribe(partnersResult => {}

Now the search function gets called.
constructor(private httpService: HttpService) { }
search(terms: Observable, params: PartnersParams) {
return terms.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => this.searchEntries(params))
.share();
}
public searchEntries(params: PartnersParams): Observable {
console.log(params);
return this.httpService.post(this.apiUrl, params)
.map((res: Response) => new PartnersResult(res.json()));
}

When string length is 3 (search gets triggered), it makes one HTTP request but then on every additional character it makes one more than the previous. 4 characters will result in 2 requests, 5 in 3 requests and so on for every new character (or backspace for that case). Debugger shows, that when searchEntries gets executed it somehow loops back into switchmap but I’m unable to solve it.

Also, without switchmap, the number of requests stays the same.

Thanks and good day.


Answer:

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *