【问题标题】:How to create a search filter in date ranges with Angular?如何使用 Angular 在日期范围内创建搜索过滤器?
【发布时间】:2020-09-15 08:17:01
【问题描述】:

问候 SO 社区。​​p>

我正在尝试在 Angular 中创建一个日期范围过滤器管道,从 API 获取数据,但它不起作用,因为它过滤了所有数据并且不显示任何数据。

我正在从 firebase 获取数据 https://loggin-app-fa0a7.firebaseio.com/data/facturas.json

这是我正在获取数据的服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class FacturasService {

  constructor(private http: HttpClient) { }

  getFacturas() {
    return this.http.get('https://loggin-app-fa0a7.firebaseio.com/data/facturas.json');
  }


}

然后我有这个管道来按日期范围过滤数据

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

@Pipe({
  name: 'filtroFecha'
})
export class FiltroFechaPipe implements PipeTransform {

  transform(row: any, f1: Date, f2?: Date): any {

    const resultadoFiltro = [];
    // si es menor a la fecha final
    if (f1 >= f2 || f1 == null) {
      return row;
    }
    // si el argumento de fecha final es invalido, se setea a la fecha actual
    if (f2 == null) {
      f2 = new Date();
    }
    // si ambos arreglos son correctos entonces se crea el nuevo arrego
    for (const filteredRow of row) {
      if (row.fecha >= f1 && row.fecha <= f2) {
        resultadoFiltro.push(filteredRow);
      }
    }
    return resultadoFiltro;


  }

}

这是我尝试应用管道的组件

   import { Component, OnInit } from '@angular/core';
import { FacturasService } from '../../services/facturas.service';


@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {

  desde = new  Date('December 25, 1995 13:30:00');
  hasta =  new Date();

  // almacena facturas
  facturas: any = [];

  constructor(private ventas: FacturasService) { }


  ver() {
    console.log('desde:', this.desde);
    console.log('hasta:', this.hasta);
  }

  ngOnInit() {
    this.ventas.getFacturas().subscribe((data: any) => {
      this.facturas = data;
      console.log('Facturas works');
      console.log('================');
      console.log(this.facturas);
    });
  }
}

这里是模板

 <!-- Header  -->
  <div class="my-auto">
    <div class="row d-flex justify-content-center mt-2 animated fadeIn">
      <p class="h1">Facturas Resientes</p>
    </div>
    <!-- Header  -->

    <!-- filtros -->
    <div class="row d-flex mt-3">

        <!-- date time picker component -->
        <form #myForm="ngForm" novalidate class="col-6">
             <input type="date"  [(ngModel)]="desde" name="desde">
      </form>

      <form #myForm="ngForm" novalidate class="col-6">
        <input type="date"  [(ngModel)]="hasta" name="hasta">
    </form>

    </div>

<div class="row mt-3">
  <button   class="btn btn-danger" (click)="ver()">Ver Fecha en consola</button>
</div>


  <!-- filtros -->

    <!-- tabla de clientes -->
    <div class="row card animated fadeIn mt-3" id="agenda">
      <table class="table table-borderless">
        <thead>
          <tr>
            <th scope="col">Empresa</th>
            <th scope="col">Monto</th>
            <th scope="col">Estado</th>
            <th scope="col">Fecha</th>
          </tr>
        </thead>
        <tbody>
          <!-- aplicando el pipe al ng-fo -->
          <tr *ngFor="let factura of facturas |filtroFecha:desde :hasta">
            <td>{{factura.empresa}}</td>
            <td>{{factura.monto | currency}}</td>
            <td>{{factura.estado}}</td>
            <td>{{factura.fecha | date}}</td>
          </tr>
        </tbody>
      </table>
   <!-- tabla de clientes -->

这是来自 firebase 的数据

    [
    {
        "empresa": "Wallmark",
        "estado": "pendiente",
        "fecha": "Thu May 28 03:19:43 UTC 2020",
        "monto": 2000
    },
    {
        "empresa": "Corte Ingles",
        "estado": "pendiente",
        "fecha": "Thu May 22 03:19:43 UTC 2020",
        "monto": 2345555
    },
    {
        "empresa": "innovatek",
        "estado": "pagada",
        "fecha": "Thu May 28 03:19:43 UTC 2020",
        "monto": 300000
    },
    {
        "empresa": "holeee",
        "estado": "pagada",
        "fecha": "Thu May 28 03:19:43 UTC 2020",
        "monto": 790000
    },
    {
        "empresa": "everlast",
        "estado": "pagada",
        "fecha": "Thu May 28 03:19:43 UTC 2020",
        "monto": 568999
    }
]

但是管道过滤了所有数据并且它没有显示在我之前创建过这种管道的视图中,但不适用于 Date 类型

这是我的项目

https://stackblitz.com/edit/github-necjgp?file=src%2Fapp%2Fservices%2Ffacturas.service.ts

我希望你能帮助我 SO comunity :(

【问题讨论】:

    标签: javascript angular typescript datetime frontend


    【解决方案1】:

    Demo我已经看到了几个问题。一个在 for 循环中,您需要编写过滤行而不是行另一个缺少转换日期应该像 new Date(filteredRow.fecha)。正如我在添加删除日期时也看到了一些问题。

    然后使用过滤方法而不是 for 循环并推送到新的循环并放置一些控件来删除日期输入的点击。

    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({
      name: 'filtroFecha'
    })
    export class FiltroFechaPipe implements PipeTransform {
      transform(row: any, f1: Date, f2?: Date): any {
        f1.toString().length == 0 ? f1 = new Date("1995-12-25T11:30:00.000Z") : f1;
        f2 == null ? f2 = new Date() :f2; 
        if (f1 >= f2 || f1 == null) { return row;}
        return row.filter(x=>{return  new Date(x.fecha) >= new Date(f1) && new Date(x.fecha) <= new Date(f2)});   
      }
    }
    

    【讨论】:

      【解决方案2】:

      我把你的管道改成了这样:

      import { Pipe, PipeTransform } from '@angular/core';
      
      @Pipe({
        name: 'filtroFecha'
      })
      
      export class FiltroFechaPipe implements PipeTransform {
      
        transform(row: any, f1: Date, f2?: Date): any {
      
      const resultadoFiltro = [];
      let date1 = new Date(f1);
      let date2 = new Date(f2);
      // si es menor a la fecha final
      if (f1 >= f2 || f1 == null) {
        return row;
      }
      // si el argumento de fecha final es invalido, se setea a la fecha actual
      if (f2 == null) {
        f2 = new Date();
      }
      // si ambos arreglos son correctos entonces se crea el nuevo arrego
      for (const filteredRow of row) {
        let a = new Date(filteredRow.fecha);
        console.log(a);
      
        if (a > date1 && a <= date2) {
          console.log("asd", filteredRow);
          resultadoFiltro.push(filteredRow);
        }
      }
      return resultadoFiltro;
        }
      }
      

      现在它可以工作了!它缺少新的 Dates() 所以它正在比较字符串。

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 2021-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        • 2020-11-09
        • 1970-01-01
        相关资源
        最近更新 更多