代码之家  ›  专栏  ›  技术社区  ›  Martina

对webapi的角无序(异步)调用

  •  1
  • Martina  · 技术社区  · 8 年前

    我有一个文本框,在每次输入时都会调用webapi。 问题是,如果我在文本框中写得稍微快一点,调用和调用的响应就会混乱。

    例如,如果我写“你好”

    • 用H调用
    • 打电话给“赫尔”
    • 打“你好”
    • 用“地狱”打电话
    • 打电话给“他”

    每个调用都管理响应数据,因此即使我写了“hello”,我也拥有与单词“he”相关的最后一个数据

    这里是密码

    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
             }
          });
    }
    

    如何管理同步呼叫,或者当用户停止数字时只进行一次呼叫?

    谢谢

    4 回复  |  直到 8 年前
        1
  •  0
  •   Goga Koreli    8 年前

    如果延迟更改输入,请使用 角反应形式 最适合这种做法。

    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">
        2
  •  0
  •   Parth Savadiya    8 年前

    尝试使用keyup事件而不是按键:

    <input type="text" class="form-control" [(ngModel)]="txtSearchModel" (keyup)="digitSearch($event)">
        3
  •  0
  •   Goga Koreli    8 年前

    对updateon blur使用ngmodelchange 而不是按键,这只会在输入失去焦点时触发事件,即下一个元素被聚焦。输入完成后将触发一次。

    <input
        type="text"
        class="form-control"
        [(ngModel)]="txtSearchModel"
        [ngModelOptions]="{updateOn: 'blur'}"
        (ngModelChange)="digitSearch($event)">
        4
  •  0
  •   D. Pesc.    8 年前

    也许使用一个如 this .

    对于这个组件,您可以使用 debounceTime operator和您也只能使用用户键入的可配置的最少字符数来启动调用。

    推荐文章