角度材料2远程自动完成.如何中止请求?
发布时间:2020-12-17 17:34:11 所属栏目:安全 来源:网络整理
导读:我正在使用Angular Material Autocomplete来根据对远程API的搜索列出结果(过滤在远程端完成). HTML方面: mat-form-field class="full-width" input type="text" placeholder="Brand" aria-label="Number" matInput [formControl]="formControl" [matAutocom
我正在使用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) ); 此时,这工作正常.我从远程获取品牌列表,我可以从自动完成列表中选择一个值.现在的问题是……每次输入文本发生变化时,如何中止所有请求? 远程请求有很多例子,但想法不是在init上获取所有远程结果.我们的想法是每次用户更改文本输入时都会获得远程结果. 解决方法
我刚刚用switchMap改变了flatMap,就像一个魅力:
this.brands = this.formControl.valueChanges.switchMap( q => this._apiService.getVehiclesBrands(q).map(x => x.results) ); 正如Benedikt在评论中所说,如果您在键入时中止XHR请求,则仍然会在服务器上执行请求,并且 – 在规模上 – 可能会导致非常高的负载.仅发出XHR是一种很好的做法,例如,在用户停止输入后500毫秒.这将减少请求数量.去做这个: this.brands = this.formControl.valueChanges.debounceTime(500).switchMap( q => this._apiService.getVehiclesBrands(q).map(x => x.results) ); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |