从api反应性角度自动完成加载



我从API完成了所有关于角度自动完成的教程,以便能够重现这些步骤。valuechanges来监听表单控件,触发switchmap来重新发送每个新关键字的请求,然后将数据加载到自动完成中。它正在工作,但在从服务加载最后一个请求后,我需要执行一个操作(计时或键入(,以在自动完成下拉列表中查看响应的最后结果。我在一个新的Angular项目上测试了它,我没有这个问题。我的Angular版本是10。

加载数据的代码:

// Search a place
search = new FormControl();
body: any;
isLoading: boolean;
errorMsg: string;
filteredPlace: any;
places = [];
minLengthTerm = 2;
selectedValue = '';
@ViewChild(MatAutocompleteTrigger) autocomplete: MatAutocompleteTrigger;    
this.search!.valueChanges.pipe(
distinctUntilChanged(),
debounceTime(500),
tap(() => { 
this.places = [];
}),
filter(value => value? true: false),
switchMap(search => 
this.placeService.searchPlace(search).pipe(catchError(() => of([]))))
)
.subscribe((val) => {
this.places = val;
console.log(val);
if (this.places.length === 0) {
// If no result we show the possibility to create a place
console.log(('No Data'));
this.autocomplete.closePanel();
}
})
onSelResult(option: any){
this.selectedValue = option.name;
console.log(option);
}
clearSelection() {
this.selectedValue = '';
this.places = [];
}

html:

<mat-form-field appearance="fill">
<mat-label>Rechercher un lieu</mat-label>
<input 
matInput
placeholder="Type de lieu, nom, adresse, département, code postal, ville" 
[formControl]="search"
[matAutocomplete]="auto"
[value]="selectedValue">
<button
matSuffix mat-icon-button  
aria-label="Clear" (click)="clearSelection()">
<mat-icon>close</mat-icon>
</button>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let place of places" (onSelectionChange)="onSelResult(place)">
<span><b>{{place.name}}</b> ({{place.zipCode}})</span>
</mat-option>
</mat-autocomplete>
<mat-hint>
Vous pouvez séparer par des virgules pour lancer la recherche sur plusieurs champs. <b>Exemple : Cimetière, 95</b>
</mat-hint>
</mat-form-field>

我不知道为什么我需要做一个操作来在自动完成下拉列表中查看请求的最后结果(对象数组(。

我之前曾尝试在Observable中加载数据以加载自动完成,并在html中使用异步管道,但当然,使用此解决方案,数据不会在值更改时发生变化。即使我用这个方法(在switchmap之后(更新observable,我也有同样的问题。

谢谢你的建议。

If最终找到了这个带有结果过滤器的例子,它运行得很好。

https://stackblitz.com/edit/angular-wazyiq-vhvssz?file=app%2Fautocomplete-simple-example.html

最新更新