Home > Back-end >  How to cancel previous http request when type in search bar
How to cancel previous http request when type in search bar

Time:10-10

I want to add some delay in making network request when I type in search bar. So I can prevent unnecessary network request.

header.component.ts

searchProduct(event: KeyboardEvent) {
    if (event) {
      const { value } = event.target as HTMLInputElement;
      this.productService.searchProducts(value).subscribe((res) => {
        console.log(res);
        if (res.length > 5) {
          res.length = 5;
        }
        this.searchResult = res;
      });
    }

product.service.ts

searchProducts(query: string) {
    return this.http.get<Prodcut[]>(`http://localhost:3000/products?q=${query}`);
  }

CodePudding user response:

The switchMap will cancel any HTTP request that hasn't been completed if a new value is emitted through the subject. You can play with the debouneTime to see what feels right for you.

this.searchBar.on('change', () => {

    of(this.serachBar.searchText).pipe(
        debounceTime(400),
        distinctUntilChanged(),
        switchMap((text) => {
            return this.productService.searchProducts(text).map(resp => {
                console.log(res);
                if (res.length > 5) {
                    res.length = 5;
                }
                return res;
            });
        });
    ).subscribe(response => console.log(response));

});

CodePudding user response:

I would suggest not to cancel the previous request, but to make a delay, if you want to prevent unnecessary network request. Something like this:

this.changeValue$
  .pipe(debounceTime(300))
  .subscribe((event) => {
    this.searchProduct(event);
  });

But in this case, you need to modify the input.

If you still want to cancel, then try:

subsription: Subscription | undefined;

searchProduct(event: KeyboardEvent) {
  if (event) {
    this.subsription?.unsubscribe();
    const { value } = event.target as HTMLInputElement;
    this.subsription = this.productService.searchProducts(value).subscribe((res) => {
    // ...
}
  • Related