Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute API call after entering 3 characters in field?

I'm working with a parent and child component. The child component has the input field and will emit the value entered by the user to the parent component like this:

<parent-component (sendInputValue)="getInputValue($event)"><parent-component>

Now in parent component I have this:

getInputField(data){
 console.log(data); // this prints the data (Example: abc)
 //  then here I'm just executing the API call ONLY if data length is 3
  if(data.length === 3){
    this.myService.getDataFromService(data).subscribe(rs=>console.log(rs));
  }
}

Now let's say this happens:

  1. The user enters: abc // API call gets execute that is good
  2. Now, user enters: abcd // No API call gets executed, that is good
  3. Now user deletes letter "d" and the new value of data will be "abc" I DONT want to execute API call again because we already execute API call for "abc"
  4. Now if the user deletes the letter "c" the new value of data is now "ab". At this point, no API call is expected
  5. Now if the user adds the letter "c" the new value will be "abc". At this point, the API call is expected. (this is working)

So how to always execute API call if input data is 3 characters and if the user enters more characters nothing should happen, and if he deletes characters and goes back to the first 3 characters nothing should happen because the API already happened? Thanks a lot in advance!

like image 807
Devmix Avatar asked Aug 07 '20 04:08

Devmix


1 Answers

I think you need distinctUntilChanged And you can use the filter in the pipe

this.myService.getDataFromService(data)
  .pipe(
    filter(_ => data.length === 3), 
    distinctUntilChanged()
  ).subscribe(rs => console.log(rs));
like image 114
Thorsten Rintelen Avatar answered Oct 16 '22 14:10

Thorsten Rintelen