Я снова задаю этот вопрос, потому что раньше я не получил четкого ответа.
Если это лучше сделать без труб, пожалуйста, покажите мне, как или укажите источник, где я могу научиться это делать.
У меня есть несколько фильтров в трубе, чтобыотфильтровать смартфоны по характеристикам.В настоящее время он работает только для одного флажка для каждой категории, но я хотел бы иметь возможность включать несколько фильтров для каждой категории (например, поиск по брендам Samsung и Apple). Этот флажок генерируется динамически на основе вызова API, поэтому яхотелось бы, чтобы труба принимала неопределенное количество аргументов.Заранее спасибо!
Я попытался выполнить цикл for внутри канала и применить массив строк в качестве аргумента.
filter-component.html
<mat-drawer-container style="overflow-y: hidden;" class="example-container">
<mat-drawer mode="side" opened>
<div class="wrapper" #wrapper>
<div class="sidebar" [ngStyle]="{'margin-left': marginSize, 'position': sideNavPosition, 'z-index':20, 'height':open===true? collapsedHeight : '100%'}">
<ul class="list-sidebar bg-defoult">
<li>
<a href="#" data-toggle="collapse" data-target=".filtermenu" class="collapsed active">
<i class="fa fa-th-large"></i>
<span class="nav-label">Filter</span>
<span class="fa fa-chevron-left pull-right"></span>
</a>
<ul class="sub-menu collapse filtermenu" data-toggle="collapse" data-target="#brandlabel" id="dashboard">
<a href="#" data-toggle="collapse" data-target="#brand" class="collapsed active" id="brandlabel">
<span class="nav-label">Brand</span>
<span class="fa fa-chevron-left pull-right"></span>
</a>
<ul class="nav-label collapse" id="brand" *ngFor="let Product of brand; let i = index">
<li class="nav-label text-light">
<input type="checkbox" name="f{{i}}" value="f{{i}}" (change)="setSearchBrand(Product)" /> {{Product}}
</li>
</ul>
</ul>
<ul class="sub-menu collapse filtermenu" data-toggle="collapse" data-target="#batterylabel" id="dashboard">
<a href="#" data-toggle="collapse" data-target="#battery" class="collapsed active" id="batterylabel">
<span class="nav-label">Battery</span>
<span class="fa fa-chevron-left pull-right"></span>
</a>
<ul class="nav-label collapse" id="battery" *ngFor="let Product of battery">
<li class="nav-label text-light">
<input type="checkbox" name="options" value="{{Product}}" (change)="setSearchBattery(Product)" /> {{Product}}
</li>
</ul>
Product-ListComponent.ts
import { Component, OnInit } from '@angular/core';
import { ProductService } from '../product.service'
import { Router } from '@angular/router';
import { Product } from '../../partner/Product';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
open: boolean;
marginSize: string;
sideNavPosition: string;
collapsedHeight: string;
brand: Product["brand"];
battery: Product["battery"];
camera: Product["camera"];
color: Product["color"];
//phoneCondition: Product["phoneCondition"];
ram: Product["ram"];
resolution: Product["resolution"];
storage: Product["storage"];
searchBrand: string = "";
searchBattery: string = "";
searchCamera: string = "";
searchCondition: string = "";
searchColor: string = "";
searchRam: string = "";
searchResolution: string = "";
searchStorage: string = "";
constructor(private productService: ProductService, private router: Router) { }
products: any[];
prod: Object[];
ngOnInit() {
this.marginSize = '0px';
this.sideNavPosition = "relative";
this.open = false;``
this.getProduct();
this.productService.brandFilter().subscribe(data => {
this.brand = data;
});
this.productService.batteryFilter().subscribe(data => {
this.battery = data;
});
this.productService.cameraFilter().subscribe(data => {
this.camera = data;
});
this.productService.colorFilter().subscribe(data => {
this.color = data;
});
this.productService.resolutionFilter().subscribe(data => {
this.resolution = data;
});
// this.productService.conditionFilter().subscribe(data => {
// this.phoneCondition = data;
// });
this.productService.ramFilter().subscribe(data => {
this.ram = data;
});
this.productService.storageFilter().subscribe(data => {
this.storage = data;
});
}
clearFilters() {
this.setSearchBrand('');
this.searchBattery = '';
this.setSearchCamera('');
this.setSearchCondition('');
this.setSearchColor('');
this.searchRam = '';
this.setSearchResolution('');
this.searchStorage = '';
}
getProduct() {
this.productService.getProduct().subscribe(
product => {
this.products = product.body;
console.log(product);
});
}
setSearchBrand(name: string) {
this.searchBrand = name;
return this.searchBrand;
}
setSearchBattery(name: string) {
this.searchBattery;
return this.searchBattery;
}
setSearchCamera(name: string) {
this.searchCamera = name;
return this.searchCamera;
}
setSearchCondition(name: string) {
this.searchCondition = name;
return this.searchCondition;
}
setSearchColor(name: string) {
this.searchColor = name;
return this.searchColor;
}
setSearchRam(name: string) {
this.searchRam = name;
return this.searchRam;
}
setSearchResolution(name: string) {
this.searchResolution = name;
return this.searchResolution;
}
setSearchStorage(name: string) {
this.searchStorage = name;
return this.searchStorage;
}
viewProducts() {
this.router.navigate(["/customers/home"])
}
detailss(product: any) {
this.productService.setProductDetails(product);
console.log(product)
this.router.navigate(["/customers/details"]);
}
details(products) {
this.router.navigate(["/customers/home"]);
}
brand-filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'brandFilter'
})
export class BrandFilterPipe implements PipeTransform {
transform(items: any[], searchBrand: string[], searchBattery: string, searchCamera: string, searchColor: string
,searchRam: string,searchResolution: string,searchStorage: string ): any[] {
if (items && items.length){
return items.filter(item =>{
if (searchBrand && item.brand.toLowerCase().indexOf(searchBrand) === -1){
return false;
}
if (searchBattery && item.battery.toString().indexOf(searchBattery) === -1){
return false;
}
if (searchCamera && item.camera.toLowerCase().indexOf(searchCamera.toLowerCase()) === -1){
return false;
}
if (searchColor && item.color.toLowerCase().indexOf(searchColor.toLowerCase()) === -1){
return false;
}
// if (searchCondition && item.phoneCondition.toLowerCase().indexOf(searchCondition.toLowerCase()) === -1){
// return false;
// }
if (searchRam && item.ram.toString().indexOf(searchRam) === -1){
return false;
}
if (searchResolution && item.resolution.indexOf(searchResolution) === -1){
return false;
}
if (searchStorage && item.storage.toString().indexOf(searchStorage) === -1){
return false;
}
return true;
})
}
else{
return items;
}
}
}
Как я уже сказал.Код в настоящее время позволяет фильтровать одну опцию из каждой категории.Я хотел бы провести рефакторинг или переделать это так, чтобы в каждой категории было несколько фильтров (например, поиск бренда и фильтра телефонов как от Apple, так и от Samsung)