Проблема фильтрации флажков [Angular] - PullRequest
0 голосов
/ 08 апреля 2019

Я создал приложение, своего рода интернет-магазин для учебных целей.Мои продукты отображаются в product.component, и мне нужно отфильтровать их по выбранным флажкам, если они соответствуют собственным продуктам.Мне удалось применить первую трубу, которая фильтрует товары по категориям (один выбор), проблема возникла, когда я попытался отфильтровать их по брендам, используя несколько вариантов.Я видел несколько примеров, похожих на мой, но здесь это не работает, и я не могу понять, как правильно настроить фильтр второй трубы.

products.component.html:

    <div *ngFor="let brand of brandList" class="checkbox">
      <input type="checkbox" (click)="filterByBrand($event, brand)">
      <label class="">{{brand.name}}</label>
    </div>

    <div>
      <span *ngFor="let category of categoryList" class="category" (click)="filterByCategory(category)">{{category.name}}</span>
    </div>

<div class="card" style="width: 18rem;" *ngFor="let i = index; let product of productList| category : categoryChoice| brand: brandChoice">
        <img src="#" class="card-img-top" alt="...">
        <div class="card-body">
          <h5 class="card-title">{{product.name}}</h5>
          <p class="card-text">Short descript: {{product.short_description}}</p>
          <p class="card-text">Full descript: {{product.full_description}}</p>
          <p class="card-text">Price: {{product.price}}</p>
          <p class="card-text">Brand: {{product.brand}}</p>
          <p class="card-text">Brand: {{product.category}}</p>
        </div>

Если бренд выбран с помощью флажка, он добавляется в массив выбранных брендов "brandChoice" в приведенном ниже коде.Я пропустил ngOnInit (), потому что не было ничего, кроме инициализации массивов продуктов, брендов и категорий.products.component.ts:

export class ProductsComponent implements OnInit {
  productList: Array<IProduct>;
  brandList: Array<IBrand>;
  categoryList: Array<ICategory>;
  sizeList: Array<string>;
  categoryChoice: string;
  brandChoice: Array<IBrand>;
  constructor(private productService: ProductService, private brandService: BrandService, private categoryService: CategoryService) {
    this.categoryChoice = '';
    this.brandChoice = [];
  }

  public filterByCategory(category) {
    this.categoryChoice = category.name;
    console.log(category);
  }
  public filterByBrand(event, brand) {
    if (event.target.checked === true) {
      this.brandChoice.push(brand.name);
    } else {
      this.brandChoice.splice(this.brandChoice.indexOf(brand.name), 1);
    }
    console.log('brandChoice:', this.brandChoice);
  }
}

категория трубы:

@Pipe({
  name: 'category'
})
export class CategoryPipe implements PipeTransform {

  transform(products: Array <any>, categoryName?: string): Array<any> {
    if (categoryName === '') {
      return products;
    }
    const sortedProducts = products.filter(product => product.category === categoryName);
    console.log(sortedProducts);
    return sortedProducts;
  }
}

марка трубы:

@Pipe({
  name: 'brand'
})
export class BrandPipe implements PipeTransform {
  transform(products: Array <any>, brandChoice: Array <any>): Array<any> {
    if (!brandChoice || brandChoice.length === 0) {
      return products;
    }
    return products.filter(product => brandChoice.includes(product.brand));
    }
  }

Структуры объектов:

{
  "products": [
    {
      "id": 1,
      "name": "Product1",
      "short_description": "fdfdf",
      "full_description": "fdsfdsfdsfdsfs",
      "price": 10.2,
      "brand": "abibas",
      "category": "women"
    },
    {
      "id": 2,
      "name": "Product2",
      "short_description": "fdfdf",
      "full_description": "fdsfdsfdsfdsfs",
      "price": 20,
      "brand": "nike",
      "category": "man"
    },
    {
      "id": 3,
      "name": "Product3",
      "short_description": "fdfdf",
      "full_description": "fdsfdsfdsfdsfs",
      "price": 30,
      "brand": "new balance",
      "category": "children"
    },
    {
      "id": 4,
      "name": "Product4",
      "short_description": "fdfdf",
      "full_description": "fdsfdsfdsfdsfs",
      "price": 40,
      "brand": "puma",
      "category": "hot details"
    },
    {
      "id": 5,
      "name": "Product5",
      "short_description": "fdfdf",
      "full_description": "fdsfdsfdsfdsfs",
      "price": 10.2,
      "brand": "abibas",
      "category": "man"
    }
  ],
  "brands": [
    {
      "id": 1,
      "name": "abibas"
    },
    {
      "id": 2,
      "name": "nike"
    },
    {
      "id": 3,
      "name": "new balance"
    },
    {
      "id": 4,
      "name": "puma"
    }
  ],
  "categories": [
    {
      "id": 1,
      "name": "man"
    },
    {
      "id": 2,
      "name": "women"
    },
    {
      "id": 3,
      "name": "children"
    },
    {
      "id": 4,
      "name": "hot details"
    }
  ]
}
...