【发布时间】:2018-07-09 13:30:20
【问题描述】:
我正在尝试使用 Angular 实现管道。下面是我尝试过的代码。我想检索唯一的完整列表。所以我为内部列表添加了一个管道过滤器名称。但我仍然得到重复的元素。我添加了 json 以供参考。内部的 ArticleTags 数组有一个对象列表。同样,每个父数组都有多个 ArticleTags 数组。我想从整个列表 ArticleTags 数组中检索唯一元素。我认为它检索特定内部列表中的唯一元素,而不是从文章标签的整个列表中检索。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterUnique',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(value: any, args?: any): any {
// Remove the duplicate elements
const uniqueArray = value.filter(function (el, index, array) {
return array.indexOf (el) === index;
});
return uniqueArray;
}
}
<ul>
<li *ngFor="let articlesResult of articlesListArray; let i=index">
<ul>
<li *ngFor="let articlesTagResult of articlesResult.ArticleTags | filterUnique; let j=index">
<i class="fa fa-times-circle" *ngIf="articlesResult.ArticleTags[j].value"></i>
<label class="form-check-label" for="exampleCheck" *ngIf="articlesResult.ArticleTags[j].value">{{articlesResult.ArticleTags[j].value}}</label>
</li>
</ul>
</li>
</ul>
getLatestArticles(currdate): void {
this.ng4LoadingSpinnerService.show();
this.ArticlesServiceCall.getArticlesDashboard(currdate)
.subscribe(
resultArray => {
this.ng4LoadingSpinnerService.hide();
this.articlesList = resultArray;
this.articlesLists = resultArray.ResponseValue;
this.articlesListArray = this.articlesLists.slice(0, 8);
},
error => console.log('Error :: ' + error)
);
}
我从articlesListArray 获取主数组数据并将其传递给html
2018 年 7 月 9 日编辑更新
使用以下管道代码获取以下错误。
从“@angular/core”导入 { Pipe, PipeTransform };
@管道({ 名称:“过滤重复” }) 导出类 FilterduplicatesPipe 实现 PipeTransform {
transform(value: any, args?: any): any {
// Remove the duplicate elements
const art = value.map( x => {
return x.ArticleTags ? x.ArticleTags.map(y => {
return y.value ? y.value : null;
}) : [];
}).reduce((acc, ele, i) => {
acc = acc.concat(ele);
return acc;
}).filter( z => {
if (z) {
return z;
}
});
return new Set(art);
}
【问题讨论】:
-
所以你循环通过
articlesListArray得到articlesResult,然后在第二个<li>标签你循环通过articlesResult.ArticleTags得到uniquearticlesTagResult,但不是使用articlesTagResult.value,而是使用articlesResult.ArticleTags[j].value? -
好的,所以我尝试使用 但它仍然检索到重复的元素。我还附上了输出的屏幕截图供您参考。第二个数组是元素列表。背部、伤害、生活方式、肩部属于一个列表。根据我的假设,它正在检索该数组中的唯一元素。但它不能与其他数组元素列表进行比较,或者我不确定。
-
好的,我现在明白了,你有文章列表,每篇文章都有标签,你想要所有文章的标签联合......对吗?
-
是的,你完全正确
-
@j4rey89 关于如何从 .ts 文件中实现的任何线索。我已粘贴 .ts 代码以供参考。