在这个垫子选项中,我将显示我订阅的可观察到的数据。
<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;
}
}谢谢
发布于 2020-11-16 09:01:36
可以使用Array#filter和Array#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属性数组除外。对其进行修改以删除重复项。
发布于 2020-11-16 08:51:35
Set对象允许存储任何类型的唯一值,无论是原始值还是对象引用。
因此,您可以转换列表,重复将被删除。
let list = [...new Set(this.filteredCustomer)];另一种使用过滤器的方法
let chars = ['A', 'B', 'A', 'C', 'B'];
let uniqueChars = chars.filter((c, index) => {
return chars.indexOf(c) === index;
});
console.log(uniqueChars); // results = [ 'A', 'B', 'C' ]发布于 2020-11-16 08:55:15
您可以使用RxJS缩减操作符来保持异步管道工作,类似于这样,假设您要根据.Cityname属性删除重复项。
public filterCity() {
var parameters = new CitySearchParameters(100, 0);
parameters.City = this.city;
this.filteredCustomer = this.customerService.get(parameters).pipe(
reduce((list, val) => {
if (!list.length) return [val]
const foundIndex = list.findIndex((item) => item.cityname === val.cityname);
if (foundIndex === -1) {
list.push(val);
}
return list;
}, [])
);
if (typeof(this.city) == "object") {
var curCity: any = this.city;
this.city = curCity.City;
}
}https://stackoverflow.com/questions/64854928
复制相似问题