角度材料2远程自动完成.如何中止请求?

Mar*_*tín 4 rxjs angular-material angular

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

TS方面:

this.brands = this.formControl.valueChanges.flatMap(
    q => this._apiService.getVehiclesBrands(q).map(x => x.results)
);
Run Code Online (Sandbox Code Playgroud)

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

远程请求有很多例子,但想法不是在init上获取所有远程结果.我们的想法是每次用户更改文本输入时都会获得远程结果.

Mar*_*tín 6

我只是改变flatMapswitchMap,并像一个魅力:

this.brands = this.formControl.valueChanges.switchMap(
    q => this._apiService.getVehiclesBrands(q).map(x => x.results)
);
Run Code Online (Sandbox Code Playgroud)

正如Benedikt在评论中所说,如果您在键入时中止XHR请求,则仍然会在服务器上执行请求,并且 - 在规模上 - 可能会导致非常高的负载.仅发出XHR是一种很好的做法,例如,在用户停止输入后500毫秒.这将减少请求数量.去做这个:

this.brands = this.formControl.valueChanges.debounceTime(500).switchMap(
    q => this._apiService.getVehiclesBrands(q).map(x => x.results)
);
Run Code Online (Sandbox Code Playgroud)