I'm able to cancel the pending HTTP request (using .unsubscribe), but after this it won't trigger my fromEvent(this.searchInput.nativeElement, 'keyup'). How do I handle it?
I'm using "fromEvent(this.searchInput.nativeElement, 'keyup')" to fetch search results. But if there is a pending HTTP request and the user clears the field, I want to cancel the request (i tried unsubscribe & it works). But, after that the 'fromEvent' won't trigger. Any idea how to handle it?
fromEvent(this.searchInput.nativeElement, 'keyup')
.pipe(
map((event: any) => {
if (event.keyCode === 17 || event.keyCode === 91 || event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40 || event.keyCode === 13 || event.keyCode === 27) {
return;
}
return event.target.value;
}),
filter((query: any) => {
if (query === '') {
this.loading = false;
this.searchedResult = [];
}
return query && query.length > 0;
}),
debounceTime(300)
,distinctUntilChanged((p, c) => {
return !!this.searchedResult && this.searchedResult.length > 0 && (p == c);
})
, switchMap(query => {
query = query.trim();
this.loading = true;
return this.cartService.searchItemByName(encodeURIComponent(query), this.shopID.shop_id.toString()).pipe(
catchError(err => {
this.toaster.error(err.error.message || "Something went wrong!");
return of([]); //in case of error let’s emit an empty array
})
);
})
).subscribe((res: any) => {
let data = res.result;
this.loading = false;
this.searchedResult = data;
if (data && data.length) this.setSelectedItem(data[0], 0)
})
SwitchMap already cancels the subscription if a new search term comes across. So I'd remove the side effects from your code and handle the empty term case not with a filter but with a conditional return.
fromEvent(document.getElementById('source'), 'keyup')
.pipe(
map((event: any) => event.target.value),
debounceTime(300),
switchMap(query => {
const trimmed = query.trim();
this.loading = true;
return trimmed === '' ? of([]) : fakeHttp(query);
})
)
.subscribe((res: any) => {
this.loading = false;
console.log(res);
});
In action: https://stackblitz.com/edit/rxjs-tg4gew?devtoolsheight=60
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments