Отфильтруйте уникальные элементы из массива, используя фильтр трубы в Angular - PullRequest
0 голосов
/ 15 мая 2018

enter image description here Я пытаюсь реализовать трубы, используя Angular.Ниже приведен код, который я пробовал.Я хочу получить уникальный для полного списка.Поэтому я добавил имя фильтра канала для внутреннего списка.Но я все еще получаю дубликаты элементов.Я добавил json для справки. Внутренний массив ArticleTags содержит список объектов.Точно так же у меня есть несколько массивов ArticleTags для каждого родительского массива.Я хочу получить уникальные элементы из всего массива списка ArticleTags.Я думаю, что он извлекает уникальные элементы из определенного внутреннего списка, а не извлекает из всего списка тегов статьи.

enter image description here

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)
      );
  }

Я получаюданные основного массива из articleListArray и их передачу в html


Редактирование обновления 9 июля 2018

Получение приведенной ниже ошибки с указанным ниже канальным кодом.

import {Pipe, PipeTransform} из '@ angular / core';

@ Pipe ({name: 'filterduplicates'}) класс экспорта 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);
}

} enter image description here

Ответы [ 3 ]

0 голосов
/ 15 мая 2018

Первый импорт в модуль

`import { FilterPipe} from 'your-custom-pipe-path';`

тогда Вы должны ввести пользовательский канал в

@NgModule({
declarations: [
     FilterPipe
    ]
})

Остальная часть кода в порядке. надеюсь, это поможет вам.

0 голосов
/ 15 мая 2018

Предполагая, что ваша статья [] выглядит так:

articles = [
    {
        ArticleTitle: 'article one',
        ArticleTags: [
            {key:0, value:'Back'},
            {key:1, value:'Shoulder'},
            {key:2, value:'Injury'},
            {key:3, value:'Abs'}]
    },
    {
        ArticleTitle: 'article two',
        ArticleTags: [
            {key:3, value:'Abs'},
            {key:1, value:'Shoulder'},
            {key:4, value:'Leg'},
            {key:5, value:'Others'}]}
]


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
        var art = value.map(x=>{
            return x.ArticleTags.map(y=>{ return y.value;});;
        }).reduce((acc,ele,i)=>{
            acc = acc.concat(ele);
            return acc;
        });
        return new Set(art);
    }
}

над конвейером возвращает набор строк, содержащий значение articletag.

<ul>
    <li *ngFor="let a of articles | filterUnique">{{a}}</li>
</ul>
0 голосов
/ 15 мая 2018

Ссылка здесь есть уникальный фильтр https://www.npmjs.com/package/ng2-pipes

  ex:   array | unique: 'Property (Optional)'
        this.items = [1, 2, 3, 1, 2, 3];
        <li *ngFor="let item of items | unique"> <!-- Array: [1, 2, 3] -->
...