网站搜索

html - 如何修复错误 TS2769:没有匹配此调用的重载


我在 Angular 中是新手……我对以下代码遇到了这个异常,并为此感到沮丧。

错误信息:

错误 TS2769:没有匹配此调用的重载。最后一个重载给出了以下错误。类型为 'City[]' 的参数无法分配给类型为 'Promise' 的参数。类型 'City[]' 缺少类型 'Promise' 的以下属性:then、catch、[Symbol.toStringTag]、finally

这是我的班级:

export class City{
    cityId:number;
    cityName:string; }

这是 TypeScript:

export class AddFlightComponent implements OnInit {
  cities:City[]=[];
  filteredOptionsD: Observable<City[]>;

  addFlightForm:FormGroup=new FormGroup({
    destinationName:new FormControl()
  });

  private _filterD(value: string): City[] {
    const filterValueD = value.toLowerCase();
    return this.cities.filter(option => option.cityName.toLowerCase().indexOf(filterValueD) === 0);
  }

func()
{
  this.filteredOptionsD = this.addFlightForm.controls['destinationName'].
  valueChanges
  .pipe(
    startWith(''),
    map(value => this._filterD(value))
  );
}

而这是我的 HTML:

<mat-form-field>
  <input type="text" placeholder=" עיר יעד" aria-label="Number" matInput formControlName="destinationName" [matAutocomplete]="auto">
  <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
    <mat-option *ngFor="let cityDestination of cities | async" [value]="cityDestination.cityId">
      {{cityDestination.cityName}}
    </mat-option>
  </mat-autocomplete>

答案#1

由于 cities 既不是 promise 也不是 observable,因此不能使用 async 管道

<mat-option *ngFor="let cityDestination of cities | async" [value]="cityDestination.cityId">

// correct
<mat-option *ngFor="let cityDestination of cities" [value]="cityDestination.cityId">

所以你应该要么移除 async 管道,要么将它绑定到异步的东西上,比如一个可观察对象