【问题标题】:Angular Material 2 Remote Autocomplete. How to abort requests?Angular Material 2 远程自动完成。如何中止请求?
【发布时间】:2018-01-03 19:03:42
【问题描述】:

我正在使用 Angular Material Autocomplete 根据对远程 API 的搜索列出结果(过滤在远程端完成)。

HTML 方面:

<mat-form-field class="full-width">
    <input type="text" placeholder="Brand" aria-label="Number"
        matInput [formControl]="formControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let brand of brands | async" [value]="brand.name">
            {{ brand.name }}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

TS方:

this.brands = this.formControl.valueChanges.flatMap(
    q => this._apiService.getVehiclesBrands(q).map(x => x.results)
);

此时,一切正常。我从远程获取品牌列表,我可以从自动完成列表中选择一个值。现在的问题是....每次输入文本更改时如何中止所有请求?

有很多关于远程请求的例子,但我们的想法不是在初始化时获得所有远程结果。这个想法是在每次用户更改文本输入时获得远程结果。

【问题讨论】:

    标签: angular rxjs angular-material


    【解决方案1】:

    我刚刚将flatMap 更改为switchMap 并且工作得像个魅力:

    this.brands = this.formControl.valueChanges.switchMap(
        q => this._apiService.getVehiclesBrands(q).map(x => x.results)
    );
    

    正如 Benedikt 在评论中所说,如果您在键入时中止 XHR 请求,请求仍会在服务器上执行,并且 - 在规模上 - 可能会导致非常高的负载。最好只在用户停止输入后 500 毫秒发出 XHR。这已经减少了请求的数量。为此:

    this.brands = this.formControl.valueChanges.debounceTime(500).switchMap(
        q => this._apiService.getVehiclesBrands(q).map(x => x.results)
    );
    

    【讨论】:

    • 在您输入时请小心取消 XHR 请求。请求仍然在服务器上执行,并且 - 在规模上 - 可能会导致非常高的负载。一个好的做法是仅在用户停止输入后 1 秒发出 XHR。这已经减少了请求的数量。
    • 我能问一下 .map(x => x.Results) 究竟做了什么吗?结果属性是什么。
    猜你喜欢
    • 1970-01-01
    • 2018-10-19
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2016-10-11
    • 2011-04-20
    相关资源
    最近更新 更多