简体   繁体   中英

Angular disordered (asynchronous) calls to webApi

I have a textbox that, at every input do a call to a webapi. The problem is that, If I write in the textbox a little bit fast, the call and the call's responses are disordered.

For Example, If I write "hello"

  • call with h
  • call with "hel"
  • call with "hello"
  • call with "hell"
  • call with "he"

Every calls manage response data, so I have the last data relative to word "he" even if I wrote "hello"

Here the code

HTML

<input type="text" class="form-control" [(ngModel)]="txtSearchModel" (keypress)="digitSearch($event)">

TS

digitSearch($event)
{
         this.modelService.searchModel(this.txtSearchModel)
         .then(response => {
         if (response && response.Code == 200) {
            //Manage Response.Data
         }
      });
}

How can I do to manage Syncrhronous call or do only one call when the user stops digit?

Thanks

尝试使用keyup事件而不是keypress:

 <input type="text" class="form-control" [(ngModel)]="txtSearchModel" (keyup)="digitSearch($event)"> 

Use ngModelChange with the updateon blur instead of keypress and this will only fire event when the input has lost focus ie next element is focused. It will be fired once when input is finished.

 <input type="text" class="form-control" [(ngModel)]="txtSearchModel" [ngModelOptions]="{updateOn: 'blur'}" (ngModelChange)="digitSearch($event)"> 

Maybe it should be useful to use a Typeahead component like this .

With this component you can use a debounceTime operator and you can also fire the call only with a min number of chars typed by user that you can configure.

For the case of delaying changes of the input, please use Angular Reactive Forms which is best fit for this practice.

 import { FormControl } from '@angular/forms'; import { debounceTime } from 'rxjs/operators'; txtSearchControl = new FormControl(); ngOnInit() { this.txtSearchControl .valueChanges.pipe(debounceTime(1000)) .subscribe(x=> this.digitSearch(x)); } 
 <input type="text" class="form-control" [formControl]="txtSearchControl"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM