【问题标题】:Angular autocomplete loading from api reactivity从 api 反应性加载角度自动完成
【发布时间】:2022-01-27 17:23:57
【问题描述】:

我从 API 完成了有关 Angular 自动完成的所有教程,以便能够重现这些步骤。 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 中使用异步管道,但当然使用此解决方案,数据不会因 valuechanges 而改变。即使我用这种方法(在 switchmap 之后)更新 observable 我也有同样的问题。

感谢您的建议。

【问题讨论】:

    标签: angular typescript angular-material autocomplete


    【解决方案1】:

    如果最终找到这个对结果进行过滤的示例并且效果很好。

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

    【讨论】:

      猜你喜欢
      • 2019-10-20
      • 1970-01-01
      • 2017-07-27
      • 2021-01-25
      • 2018-10-31
      • 2021-02-05
      • 2017-11-29
      • 2019-01-31
      • 2023-03-17
      相关资源
      最近更新 更多