【问题标题】:Material Autocomplete Angular Stopping Api Call when Selected From the Autocomplete Dropdown options从自动完成下拉选项中选择时材料自动完成角度停止 API 调用
【发布时间】:2019-01-31 14:27:40
【问题描述】:

我正在使用 Material Angular 自动完成下拉功能在我的下拉列表中填充位置预测。我正在使用材料的 onChange 从我创建的服务中调用 api。我的问题是,当我从选择框中选择预测时,会向节点服务器触发 api 调用,因为 onChange 再次被触发。因此,当从下拉列表中选择一个选项时,我想停止对服务的 Api 调用。 这是模板的代码!!

    <mat-form-field>
       <input matInput type="text" name="location" placeholder="Search By Location" aria-label="Location" [matAutocomplete]="auto" formControlName="location">
       <mat-autocomplete #auto="matAutocomplete" [displayWith]="location">
         <mat-option *ngFor="let places of predictions" (optionSelected)="predictionSelected($event)" [value]="places.description">
           <span>{{places.description}}</span>
         </mat-option>
       </mat-autocomplete>
   <mat-form-field>

在我的 component.ts 中,我编写了一个函数,该函数将调用我的谷歌地图服务并获取我的 onChange 预测。我创建了一个事件函数,它是 (optionSelected),当下拉列表中的值被选中时触发。

predictionFilled = false;
ngOnInit() {
    this.customForm.get('location').valueChanges.subscribe(
      (value) => this.onChangeLocation(value)
    );
  }

  onChangeLocation(location) {
    if ( this.predictionFilled ) {
      return;
    }
    this.googleMapsService.suggestPlaces(location);
    this.placesPredictions = this.googleMapsService.getPredictionsUpdateListener().subscribe((predictions: Places[]) => {
      console.log(predictions);
      this.predictions = predictions;
    });
  }

  predictionSelected(event: any) {
    this.predictionFilled = true;
  }

问题是,当我从下拉菜单中单击选项时,事件 (optionSelected) 在 valueChanges 事件之后触发。从技术上讲,事件 optionSelected 应该在 onChange 之前触发,但我不明白为什么事件 valueChanges 在 optionSelected 事件之前触发。

【问题讨论】:

  • 伙计们,你也可以给我一些其他的实现方法!!
  • 为什么不从form valueChanges 事件中调用predictionSelected()?这样你就不需要注册(optionSelected)事件了。
  • 我该怎么做?你能帮我写一些代码吗?

标签: javascript angular angular-material


【解决方案1】:

predictionSelection() 内部的 event 没有任何作用。

您可以简单地在 formControl valueChanges 事件中编写该单行,然后从注册它的 mat element 中删除 (optionSelected)="predictionSelected($event)"。也不需要predictionSelected(event : any) 方法。

要停止调用api调用,可以检查输入的值是否存在于predictions数组中,然后再做决定。

this.customForm.get('location').valueChanges.subscribe(
      (value) => {
           if (this.predictions.findIndex(value) > -1) {
                  this.predictionFilled = true; // value exists, then do not make api call
           }
           else {
                this.predictionFilled = false; // make api call
           }
           this.onChangeLocation(value);
      }
 );

【讨论】:

  • 这样不行!由于这不会发送任何 Api 调用,因此在更改位置输入值时设置为 true 会将 predictionfilled 设置为 true,而且我认为我无法使用该语法设置 prediction 填充为 true。我想要的是,当用户在输入字段中键入时,API 会得到建议,然后当用户从下拉列表中选择某些内容时,应该避免 api 调用!如果这不是正确的方法,您可以建议我使用其他方法来实现此功能。
  • 感谢您指出错误的语法并检查更新的答案。
  • 非常感谢。这是一个简单的问题,我只需要将预测数组值与所选值进行比较并切换布尔值。
  • 是的,它发生了。有时我们试图忽略简单的问题,使它们变得复杂:)
猜你喜欢
  • 2017-07-14
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多