首页 > 解决方案 > 如何在Angular 6中实现按价格范围过滤?

问题描述

我有一个手表电子商务网站,价格从 20 美元到 60 美元不等。该项目是在 Angular 6 和 Firebase 作为数据库中开发的。我想按价格范围过滤产品,即 20 以下、20 -30、30 - 40 等...

以下是价格过滤器使用的文件 1. product-fliter.component.html

<div class="list-group">
        <a class="list-group-item list-group-item-action"
        [class.active]="!price" routerLink="/">
          All Price
        </a>
        <a *ngFor="let p of price$ | async" 
        class="list-group-item list-group-item-action"
        routerLink="/" [queryParams]="{ price : p.key}"
        [class.active]="price === p.key">     
              {{p.name}}
        </a>
</div>
  1. 产品过滤器.component.ts
price$;
  @Input('price') price;

constructor(priceService: PriceService) { 
    this.price$ = priceService.getPrice();
  }
  1. 价格.服务.ts
itemRef : any;

  constructor(private db: AngularFireDatabase) {}

  getPrice() {
    this.itemRef =  this.db.list('/price').snapshotChanges().pipe
    (map(changes => { return changes.map(c => ({ key: c.payload.key, 
    ...c.payload.val() }));
    }));
    return this.itemRef;  
  }
  1. home.component.ts(这是我应用过滤逻辑的地方)
private populateProducts() { 
    this.productService.getAll().subscribe(products => {
      this.products = products;

      this.route.queryParamMap.subscribe(params => {

          if(params.get('price') || this.price) {
          this.price= params.get('price');
          this.applyFilterPrice();
        } 
      });
    }); 
  }

以下是供参考的图像, 我希望产品按价格过滤。任何更改或任何修改都会很好。我想知道价格范围滑块的工作原理及其在 Angular 6 中的代码。Firebase 价格范围 产品现场查看

标签: angularfirebaseangular6

解决方案



private populateProducts() { 
    this.productService.getAll().subscribe(products => {

      // here is where you can filter
      this.products = products.filter(product => {
         return product.price >= this.minimumPrice
             && product.price <= this.maximumPrice
       });

      this.route.queryParamMap.subscribe(params => {

          // Can you clarify why you use this if conditional ?
          if(params.get('price') || this.price) {
          this.price= params.get('price');
          this.applyFilterPrice();
        } 
      });
    }); 
  }

我希望这对您的情况有所帮助,但请注意,这样做只会过滤前端的产品,您仍然可以从 firebase 加载所有产品。


推荐阅读