Pause before sending each request

How can we optimize the Async Validator so that it only sends a request to JSON once, instead of every time a letter is typed in the Email form?

isEmailExist(): AsyncValidatorFn  {
   return (control: AbstractControl): Observable<any> => {
     return this.usersService.getUserByEmail(control.value).pipe(
        debounceTime(2000),
        map(users => {
            if (users.some(user => user.email.toLowerCase() === control.value.toLowerCase())) {
               return { isExist: true };
            } else {
               return null;
            }
        })
     ) 
   }
  }

Answer №1

To properly utilize the debounceTime operator, it should be connected after an Observable that triggers keyup events. One method to accomplish this is by employing the fromEvent operator.

Answer №2

Merei, you have the option to utilize {updateOn:'blur'}, please refer to the documentation

Alternatively, you can skip using a validator and instead verify isEmailExist during submission

You could also "check" the email with a debounceTime when the value changes. Suppose you have a variable called "check" and a control

  check=false;
  control=new FormControl('',Validators.required,this.customValidator().bind(this))

The bind(this) allows you to access a variable within your component, so your customValidator could be structured like this

  customValidator(){
    return (control) => {
      if (!this.check)  //if the variable in component is false return of(null)
        return of(null)
      else { //else call the service
        return this.usersService.getUserByEmail(control.value).pipe(
           map(users => {
              if (users.some(user => user.email.toLowerCase() === control.value.toLowerCase())) {
                  return { isExist: true };
              } else {
                 return null;
              }
           })
         )
       }
    }
  }

Now, after setting up the FormControl, you can subscribe to valueChanges

this.control.valueChanges.pipe(debounceTime(300)).subscribe(_ => {
  this.check=true;
  this.control.updateValueAndValidity({emitEvent:false});
  this.check=false;
})

In this stackblitz example, I demonstrate calling your service with a dummy function

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

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selectionChange($event){ let array ...

HTML link with "mailto:" not opening in a new tab

Just posted for the first time! I'm attempting to create a mailto link using 'templated' JavaScript that pulls specific data from a JSON object: var menu = { "menu": [ { "title": "let's talk", "link": "mailto:<a href ...

Encoding and Displaying Characters in HTML with UTF-8

I am experiencing an issue with UTF-8 characters in the page title. I would like to include the music symbol ♫ on the page title. The strange thing is that sometimes it displays correctly (in Google Chrome) and other times it shows a square symbol indic ...

Troubleshooting why @HostListener seems to be malfunctioning

I implemented a drag event listener using the HostListener to determine if an element is being dragged inside or outside of the browser window. When the element is dragged inside the window, a "drop zone" div displays the message "Drop your files here". Ho ...

Navigating the jQuery Search Form: Redirecting to Pages within your Website

After successfully creating my first Javascript search form with an Autocomplete Script, I am facing a challenge. I want to enable users to press "enter" after searching for a product and get redirected to the corresponding product URL page. The operation ...

What are some effective ways to stretch specific muscles?

I am facing an issue with my select element. The default value is "please choose," but there are options like "Accommodation & Hotels" that are longer and not clearly visible on IE browsers, though they work fine in Firefox. How can I resolve this issue? S ...

Interactive Sidebar Navigation Content

On my website, I have a navigation sidebar that contains links to all of the main site pages. Each page has the same links, except the link to the current page is not included, making it easy to visually identify which page you are on. Currently, I manuall ...

Issues stemming from cross-domain AJAX have resulted in errors with Karma and Jasmine

I've been working on configuring tests that utilize Jasmine and Karma to test my JavaScript code. Karma operates in Node.js and initiates a Chrome browser for testing purposes. Unfortunately, I keep encountering an error message that reads "Chrome 28 ...

Using a function as a parameter in Typescript: Anticipated no arguments, received 1.ts

I'm encountering an issue when trying to pass the doSomething function into performAction. The error message I'm receiving is Expected 0 arguments, but got 1 interface SomeInterface { name: string, id: string } function doSomethingFunction( ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

Using "http2" in Angular 7 is imperative for improving network performance and enhancing speed

Seeking to implement http2 on the client side of my Angular project. const http2 = require("http2"); const client = http2.connect("http://localhost:8443"); const req = client.request({ ":path": "/" }); Encountered an error when attempting an http2 r ...

I am seeking guidance on retrieving the value of a text box that is activated by a radio button through jquery within the provided code

When conducting my test case, the user is presented with a choice between ielts and toefl. If the user chooses ielts, an input box appears where they can enter their ielts score. My goal is to extract and store the value entered in that input box. Check ou ...

Is the form being submitted with the href attribute?

Does this code ensure security? <form id="form-id"> <input type='text' name='name'> <input type='submit' value='Go' name='Go'/></form> <a href="#" onclick="docume ...

Require users to sign in immediately upon landing on the homepage in Next JS version 13 or 14

I have created a traditional dashboard application using Next.js 13 with a pages router that places all pages behind the /dashboard route, such as /dashboard/users, /dashboard/orders, and so on. I want to ensure that when a user visits the website, a fork ...

The Javascript function call from the <img src="myFunction()"> is malfunctioning

I am looking to dynamically pass the URL of an image using a JavaScript function. <head> <script> function myFunction() { var str1 = "somepictureurl.png"; return str1; } </script> </head> <body> <img src="myFu ...

Cannot use Axios instance in Next.js due to error stating 'Localstorage is not defined'

I am currently working on a React app and have created an Axios component that I would like to reuse: import axios from 'axios' import dynamic from 'next/dynamic' const baseUrl = 'http://127.0.0.1:8000/' const axiosInstan ...

What are the steps to integrate my server-side PHP code into this form wizard?

Having created a straightforward 3 step form wizard for registration, I encountered an issue at the last stage when users click on submit. The desired action is to direct users to the PHP code that has been written. Update: Despite updating the HTML code ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

The MUI multiple select feature is experiencing issues following the addition of a new button

I'm having trouble adding buttons below a select dropdown menu with a specific height. When I try to put the menu item inside a div, the multiple select stops working and I have no idea why. Can someone help me figure this out? Check out my CodeSandb ...

The language in the React Native app remains unchanged despite utilizing i18next.changeLanguage

I am currently attempting to integrate the i18next library into my React Native app in order to facilitate language changes, but I have encountered difficulties with translation. image description here I have created an i18n.tsx file. import i18next from & ...