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

Displaying a Countdown in a Django Loop: A Step-by-Step

Hey there, I've got a Javascript countdown nested in a Django for loop that's causing some trouble by displaying multiple instances. Currently, only the first countdown works when I click on any of the start buttons. I'd like each button to ...

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

Is there a way to prevent ng-template-loader from scanning image src's?

Currently, I am beginning to incorporate webpack into my development workflow for an angular project. To create my templateCache, I have had to include the ng-template-loader. Below is a snippet of my webpack configuration: { test: /\.html$/, loa ...

What is the preset value for the payload in a vuex action?

Currently, I am utilizing an if-else statement in my Vuex action to set a default value for a payload property. Specifically, I check if the passed payload object contains a delay property; if it does not, I assign it a default value and handle appropriate ...

The message vanishes upon refreshing the page

I've developed a socket.io web app. When I click on the button to send a message, the message appears briefly but disappears when the page refreshes unexpectedly. How can I prevent this random refreshing and ensure that socket.io saves my messages? B ...

Failure to showcase AJAX JSON data on DataTable

Issue with DataTable and AJAX JSON Data I have been encountering an issue while working on a project that involves using DataTable to display POST data via AJAX. The problem I am facing is that all the records are being displayed without pagination, even ...

Can you identify the issue with the phase control in my sine wave program?

I have recently developed an interactive sine wave drawing web application. Below is the code snippet for reference: const canvas = document.getElementById("canvas"), amplitude_slider = document.getElementById("amplitude_control"), wavelength_slider ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...

What is the best way to extract all Enum Flags based on a Number in TypeScript?

Given: Enum: {1, 4, 16} Flags: 20 When: I provide the Flags value to a function Then: The output will be an array of flags corresponding to the given Enum: [4, 16] Note: I attempted to manually convert the Enum to an array and treat values as numb ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

Dynamic modal in Vue JS with custom components

Within the news.twig file {% extends 'layouts.twig' %} {% block content %} <section class="ls section_padding_bottom_110"> <div id="cart" class="container"> <cart v-bind:materials=" ...

The designated function name can be either "onButtonClick" or "onClickButton"

I am a Japanese developer working on web projects. Improving my English language skills is one of my goals. What would be the correct name for a function that indicates "when a button has been clicked"? Is it "onButtonClick"? Maybe "onClickButton"? Co ...

The `note` binding element is assumed to have an unspecified `any` type

I'm encountering an error that I believe is related to TypeScript. The issue arises when trying to work with the following example. I am using a JavaScript server to import some notes. In the NoteCard.tsx file, there is a red line under the {note} cau ...

invoking a function in one component from another component within an Angular 4 project using ng-smarttable

Utilizing ng-smarttable to display data in a table and have successfully added a custom button in a separate component. However, I am encountering an issue where the data does not reload when clicking on the button. An error message is appearing: ERROR Ty ...

Gridster2 for Angular: Resolving Overlapping Grid Items during Drag

The Angular version being used is 4.0.0 The angular-gridster2 library version being used is 2.10.0 When dragging the items randomly over other items, they become overlapped (as shown in the image below) The circled numbers represent the number of column ...

Enhancing Angular Directives with Dynamic Templates upon Data Loading

I am facing an issue with a directive that is receiving data from an api call. While the directive itself functions properly, the problem seems to be occurring because the directive loads before the api call is complete. As a result, instead of the expecte ...

The ValidationSchema Type in ObjectSchema Seems to Be Failing

yup 0.30.0 @types/yup 0.29.14 Struggling to create a reusable type definition for a Yup validationSchema with ObjectSchema resulting in an error. Attempting to follow an example from the Yup documentation provided at: https://github.com/jquense/yup#ensur ...

Submitting an array of objects via HTTP PUT

Struggling to find a way to update a list of Objects on MongoDB in one method call within the Submit button. Spent all day yesterday attempting, but it seems to be unsuccessful. The goal is to update all product sells in the database by entering values for ...

Implementing the react-i18next withNamespaces feature in Ant Design forms

I'm a newcomer to i18next and TypeScript, and I'm trying to translate an antd form using withNamespaces. export default withNamespaces()(Form.create()(MyComponent)); Encountering the following error: Argument of type 'ComponentClass< ...

Accepting PHP multidimensional array through ajax

My PHP code includes a script to open a database, fetch data, and encode it into JSON format. include_once($preUrl . "openDatabase.php"); $sql = 'SELECT * FROM dish'; $query = mysqli_query($con,$sql); $nRows = mysqli_num_rows($query); if($nRow ...