角度删除可观察到的重复项

federico.bessi

在这个mat选项中,我尝试显示我已订阅的可观察数据。

   <mat-option *ngFor="let option of (filteredCustomer | async)?.Items"
   [value]="option" (onSelectionChange)="searchDest($event)">
   {{option.Cityname}} 
   </mat-option>

可观察对象的名称为filteredCustomer。

现在在mat选项中,我尝试显示城市名称。那就是结果。

Los Angeles
Boston
Detroit
Los Angeles
Washington
Los Angeles

如您所见,我有重复项。

是否可以删除重复项(如sql中的非重复项)?

我的观察结果来自以下ts文件:

public filterCity() {
 var parameters = new CitySearchParameters(100, 0);
 parameters.City = this.city;    
 this.filteredCustomer = this.customerService.get(parameters);
 if (typeof (this.city) == "object") {
  var curCity: any = this.city;
  this.city = curCity.City;
 }
}

谢谢

迈克尔·D

您可以使用Array#filterwithArray#findIndex删除数组中的重复项。

// credit: https://stackoverflow.com/a/36744732/6513921
private uniqueArray(target: Array<any>, property: any): Array<any> {
  return target.filter((item, index) =>
    index === target.findIndex(t => 
      t[property] === item[property]
    )
  );
}

然后,您可以使用map运算符“捕获”控制器中可观察对象的发射,并在将它们呈现在模板中之前将其删除

public filterCity() {
  var parameters = new CitySearchParameters(100, 0);
  parameters.City = this.city;
  this.filteredCustomer = this.customerService.get(parameters).pipe(
    map(customer => ({
      ...customer,
      Items: uniqueArray(customer.Items, 'Cityname')  // <-- remove duplicates by `Cityname` property
    }))
  );
  if (typeof (this.city) == "object") {
    var curCity: any = this.city;
    this.city = curCity.City;
  }
}

散布运算符...用于保留除Items属性数组之外的可观察发射中的其他属性它被修改为删除重复项。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章