Using debounceTime and distinctUntilChanged in Angular 6 for efficient data handling

I recently came across a tutorial on RxJS that demonstrated the use of debounce and distinctUntilChanged. I'm trying to implement it in Angular 6, but I'm facing some challenges.

Here is the code from the tutorial:

var observable = Rx.Observable.fromEvent(input,'input');

observable.map(event=>event.target.value)
    .debounceTime(2000)
    .subscribe({
        next:function(value){
        console.log(value)
    }
}

This is my attempt at implementing it:

In the HTML file:

<input class="form-control" [(ngModel)]="userQuestion" type="text" name="userQuestion" id="userQuestions">

In the TypeScript file:

import { Subject,Observable } from "rxjs";
import { debounceTime,distinctUntilChanged } from "rxjs/operators";

ngOnInit() {
    // initialization
    this.userQuestion = new Observable;
    this.userQuestion.pipe(
        debounceTime(2000)).subscribe(val => {
            console.log(val)
        }
    )
}

However, my implementation does not seem to work correctly. Can anyone provide guidance on how to make it work?

Answer №1

There are two important things to remember:

In your typescript file, make sure you initialize your Observable correctly. To create an Observable based on a DOM event like 'input', use the 'fromEvent' method.

Additionally, remember that pipe is used to chain operators together and should not contain a subscribe function.

UPDATE

If you are using @ViewChild, remember to create the Observable in ngAfterViewInit as ViewChild won't be accessible before that point.

In your template:

<input #questionInput class="form-control" [(ngModel)]="userQuestion" type="text" name="userQuestion" id="userQuestions">

In your .ts file:

@ViewChild('questionInput') questionInput: ElementRef;

public input$: Observable<string>;

////
  ...your code here...
////

ngAfterViewInit() {
   this.input$ = fromEvent(this.questionInput.nativeElement, 'input')
      .pipe(
         debounceTime(2000),
         map((e: KeyboardEvent) => e.target['value'])
      );

     this.input$.subscribe((val: string) => {
         console.log(val)
      });
}

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

Setting a default value for NULL property in TypeScript

Trying to establish a default value for all NULL objects has been quite the challenge. The current code looks like this: private setDisplayAmount(summaries: summary[]): void { summaries.map(t => { // performing some operations, and then... ...

Handling Promises in Angular 1 App using Typescript ES6/2015

Currently, I am working on an Angular 1.5 application that utilizes Typescript. My main concern is finding the most efficient way to handle ng.IPromise compared to Promise (ES6 promise). Personally, I would prefer to solely deal with the ES6 Promise type. ...

It is not possible to use an async function with Ionic 4 ToastController buttons

Incorporating a new function into the handler of my ToastController button to return a promise (in this case: this.navCtrl.navigateForward()) is something I need assistance with. This is what my code looks like: const toast = await this.toastController.c ...

What is the best way to search and sort a MatTable with special characters like accents and diacrit

I need to implement a name filtering functionality for a table, regardless of whether the user includes accents or not. For instance: If the user types "hydrogen", the result should display "Hydrôgen" from the table. I am using Angular 8.1.3 and Angula ...

Error: The argument passed to the function must be an Array type. Undefined value was received instead of an array

Looking for some assistance with this coding issue, hoping someone with expertise can lend a hand! (Not my forte) I've written this Typescript code snippet for a basic CloudFunction export const add2list = functions.https.onRequest((req:any , res:any ...

Is it possible for Angular components to retrieve information on the current route and parameters?

I am struggling to understand why it's so difficult... why we are not supposed to care about the route from outside the routed component.... HOWEVER: I am attempting to develop a service so that my header (and any other component) can have access to ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

Enumerate all interdependencies among 2 directories or libraries in an Angular application

I am currently working on a large Angular project and need to refactor some code by identifying dependencies between two specific folders/libs (using nx). Here is an example of the file structure: /apps /lib-1 a.service.ts b.component.t ...

Utilizing the 'create' function in sqlite each time I need to run a query

I've been diving into SQLite within the Ionic framework and have pieced together some code based on examples I've encountered. import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-a ...

The process of obtaining the selected option with ElementRef

One of the features in my table is the ability to add dynamic rows using an ADD button. I used a form array to create this table structure. Each row includes a select box with a list of options. Situation When a user selects an option from the select b ...

What steps are needed to develop a TypeScript component within Angular framework?

I've been attempting to develop an Angular Component in TypeScript. I'm trying to utilize document.createElement to build a toolbar within my component, but it's not appearing. Below is my Component code: import {Directive, Component, boot ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

How can we ensure that only one of two props is specified during compilation?

I've designed a customized Button component. interface Button { href?: string; action(): void; } I'm looking to ensure that when a consumer uses this Button, they can only pass either href or action as a prop, not both. I want TypeScri ...

Is the async pipe the best choice for handling Observables in a polling scenario

The situation at hand: I currently have a service that continuously polls a specific URL every 2 seconds: export class FooDataService { ... public provideFooData() { const interval = Observable.interval(2000).startWith(0); return interval ...

Display corresponding JSON images of items within an *ngFor loop in Angular

For my latest project, I am using Angular for the front-end and Laravel for the back-end. The issue I'm facing is with displaying images in Angular that are stored in Laravel storage. The image URLs are stored in the database in JSON format like this: ...

Generate a data type automatically based on an Array

Imagine having an imaginary api that provides color values based on user selections. Consider the following arrays with string values: const Colors1 = ['red', 'blue', 'purple']; const Colors2 = ['blue', 'white& ...

How can I incorporate multiple quality sources into a flowplayer using Angular?

Is there a way to add multiple sources with different qualities like 1080p, 720p etc.? Thank you in advance. flowplayer('#my_player', { src: '../assets/videos/video_1080p.mp4', // title: 'This is just demo&apo ...

CDNify load error causing Grunt Serve to fail

I have encountered an issue with a freshly installed Angular project. When I try to run the grunt serve command, I receive the following error: I am currently using Node 12.6.1 with Source Tree and have confirmed that Bower is properly installed. Loading ...

What is the best way to showcase the outcome of a function on the user interface in Angular 2?

The code snippet below was originally in my .component.html file: <div class="someContainer"> <div class="text--bold">Display this please:</div> <div>{{ myObject.date ? '2 Jun' : 'Now' }}</div&g ...

What are some solutions to the "t provider not found" error?

Upon deploying my application on the production server using GitLab/Docker, I encountered the following error message: ERROR Error: No provider for t! at C (vendor.32b03a44e7dc21762830.bundle.js:1) at k (vendor.32b03a44e7dc21762830.bundle.js:1) at t._thr ...