"Encountering a problem with the debounceTime operator in rxjs and HTTP requests while using the keyup

I have been working on implementing server-side search in Angular 7. I managed to find some code for implementation, but unfortunately it is not functioning as expected. The issue I am encountering is that when searching for a string, the code sends multiple HTTP requests instead of just one. Below is the section of my code where this problem occurs.

    fromEvent(this.simpleSearchInput.nativeElement, 'keyup').pipe(
      debounceTime(500),
      switchMap((search: any) => {
        return this.usersService.simpleUserSearch(search.target.value);
      })
    ).subscribe(res => {
      this.queryUsers = res.result.data;
      console.log('User Name is :' + res);

    }); 
  }

Answer №1

Here is a basic example inspired by your code. Experiment with the timing of debounceTime and delay to observe how it impacts the functionality:

const { timer, fromEvent, of } = rxjs;
const { debounceTime, map, switchMap, delay, tap } = rxjs.operators;


const inputElement = document.getElementById('the-input');

fromEvent(inputElement, 'input').pipe(
  map(e => e.target.value)     // retrieve value from input
  , tap(console.info)        // log real-time input changes
  , debounceTime(1000)       // time until action
  // mimic extended server request {{{
  , switchMap(query => of(query.toUpperCase()).pipe(
      tap(result => console.info('[requested]', result)),
      delay(2000),         // simulated server response time
      tap(result => console.info('[returned]', result))
  ))
  // }}}
).subscribe(response => {
  console.log('The result is: ' + response);
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55272d3f2615637b617b65">[email protected]</a>/bundles/rxjs.umd.min.js"></script>

<input
  id="the-input"
  type="text"
  placeholder="Start typing"
  />

Answer №2

After some research, I stumbled upon this code snippet that works flawlessly. Instead of using the RXJS library, I opted to leverage lodash for this functionality.

Here are the steps to implement it:

1. Begin by importing debounce in your component's TypeScript file:

import { debounce } from 'lodash';

2. Create a private property:

private debouncedFunction: any = null;

3. Integrate the debouncedFunction into your existing function:

 search(event: any) {
    if (this.debouncedFunction) {
      this.debouncedFunction.cancel();
    }
    this.debouncedFunction = debounce(() => {
      console.log(event); // The event value will be printed after a 1-second pause in typing
    }, 1000);

    this.debouncedFunction();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The element is inferred to have the 'any' type. No index signature matching the parameter type 'string' was found on the 'User1' type

I have been experimenting with computed properties in TypeScript, but I've encountered a specific issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User1'. ...

Consequences of eliminating Angular component wrapper tags from the DOM

Imagine there is a component named <hello-world> with the following HTML template: <div>Hello World!</div> When this component is used and inspected in the DOM, it shows up like this: <hello-world> <div>Hello World!</div ...

Using TypeScript to separate namespaces

tsconfig.json: ... "module": "none" ... file1.ts: namespace Myns { type Mytype = number } file2.ts: namespace Myns { let x: Mytype ^^^^^^ Error - unable to locate declaration in file1.ts } Why am I encountering an error when trying to us ...

Utilize Typescript to seamlessly transfer data between middleware stages

This is my first time creating an Express app using Typescript. I attempted to transfer data between middleware as I usually do in a JavaScript Express app In my JavaScript application, passing data was seamless What am I doing incorrectly here? Where h ...

How to toggle visibility of child elements in an HTML template using Angular 4+

I'm currently working on incorporating a basic "hover over a comment to display a reply button" feature in my angular application. Is it possible to create this effect using template reference variables exclusively? Something like this... <mat-l ...

Issue encountered while generating menu using Angular's Material framework

In my Angular project, I am working on creating a right-side menu with specific functionalities. While the Home and Photo menus work perfectly, I am encountering an issue with the Admin menu. I intend to have 2 submenus open when clicking on the Admin tab, ...

Exploring the optimal procedures to asynchronously request an external API in Node.js using TypeScript

When handling a POST API request in a Node.js application built using TypeScript, it's necessary to make a call to an external API. This external API operates independently and must run in the background without impacting the response time. How can t ...

Exploring Node.js Express: Accessing HTTP headers prior to sending them

In my current Node.js project utilizing the Express web server plug-in, I am looking to track the total data being sent by the web server. This involves retrieving the 'Content-Length' field from an outgoing HTTP header immediately after adding t ...

What is preventing me from using the "@" symbol to substitute the lengthy relative path in my __tests__ directory?

https://i.sstatic.net/U1uW3.png When I initialized my Vue project using vue-cli, I encountered an issue where the use of @ in my src folder was functioning correctly, but not in my __tests__ folder. I have already added configurations to my tsconfig.json ...

Adjusting table to include hashed passwords for migration

How can I convert a string password into a hash during migration? I've tried using the following code, but it seems the transaction completes after the selection: const users = await queryRunner.query('SELECT * FROM app_user;'); user ...

What is the best way to retrieve the instance of a different component?

This question is not specifically referring to a child component, and therefore using ViewChild is not an option. The query here is if it's feasible to inject any component into another component. There was a related discussion on Stack Overflow, but ...

What is the best way to retrieve the input value from a moment object?

Upon receiving a date from the server, I noticed that the time is correct in the _i variable but rounded to 00:00 in the d variable below. How can I access the value in the _i variable? this.xxxxxStartDate = moment( data.xxxxxStartDate ).format("Do M ...

The element ion-virtual-scroll is unrecognized

<ion-virtual-scroll [items]="churchNewsList" approxItemHeight="120px"> <ion-item *virtualItem="let news"> {{ news }} </ion-item> </ion-virtual-scroll> I encountered an issue with the following error messag ...

After updating the state in a Reducer with Redux Toolkit, make sure to utilize a

Issue: Seeking efficient code writing methods. Here is a detailed example of my Redux Toolkit slice below: import { createSlice } from '@reduxjs/toolkit'; import { setCookie } from '../../utils/storageHandler'; const initialState = { ...

When HTMLElement focus is activated, it interrupts the flow of execution

(the code presented is in TypeScript and I'm working with Angular 5, but I don't think that's the issue, so prove me wrong!) I have a basic input field that triggers events in an Angular component. (EDIT: I've added the complete compo ...

Utilizing Typescript to inject dependencies and receive arguments within a class

I am currently using InversifyJS with the container. My goal is to inject the templateEngine and provide args (such as host, port, etc...) in the constructor. const container = new Container(); container.bind<MailerInterface>(TYPES.Mailer).to(NodeM ...

Issue in kendo-angular-upload: Failure to trigger error event following a 500 Server Error Code

When developing the Front End, I utilize Angular 7 to attempt uploading an image using Kendo: <kendo-upload [saveUrl]="uploadSaveUrl" [removeUrl]="uploadRemoveUrl" [restrictions]="uploadRestrictions" [mul ...

Tips for modifying the export csv file name in primeng when initiating the download process

Here is a prime ng table of angular: The records are listed using the primeng table library, and you can also download csv. <p-table #dt styleClass="table table-striped" [columns]="colsCSV" [value]="reviewSSRList" selectionMode="single" [paginator]=" ...

Pausing or buffering an RxJS 6 observable when the page is inactive

Currently, I am dealing with a stream of letters that need to be arranged in the correct order to form a word. However, an issue arises when the user switches tabs, minimizes the browser, or switches applications - the behavior mimics using setTimeout(), r ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...