简体   繁体   English

Angular 8: Pipe 隐藏过去的事件不起作用

[英]Angular 8: Pipe to hide past events doesn't work

I created a checkbox in my template to hide all elements that have been taken place earlier than today depending on the bookingEnd in my JSON data.根据我的 JSON 数据中的bookingEnd ,我在模板中创建了一个复选框,以隐藏比今天更早发生的所有元素。 The recent-filter.pipe.ts pipe should filter all past events. recent-filter.pipe.ts pipe 应该过滤所有过去的事件。

To my problem, I get an error TS2365: Operator '>' cannot be applied to types 'number' and 'Date'.对于我的问题,我收到error TS2365: Operator '>' cannot be applied to types 'number' and 'Date'. in advance in the pipe and no data gets displayed on my template.提前在 pipe 中,并且没有数据显示在我的模板上。 The whole scenario works in pure JavaScript, so I think that bookingEnd is definitely a date object.整个场景在纯 JavaScript 中工作,所以我认为bookingEnd绝对是一个日期 object。

Can you help me why there is no data after applying the pipe filter?你能帮我为什么应用pipe过滤器后没有数据吗?

JSON Data: JSON 数据:

{
  bookingStart: "2019-10-27T23:00:00.000Z",
  bookingEnd: "2019-12-29T23:00:00.000Z",
  city: "Manhattan",
  confirmed: false,
  country: "UK"
}

recent-filter.pipe.ts:最近过滤器.pipe.ts:

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

@Pipe({
  name: 'recentFilter'
})
export class RecentFilterPipe implements PipeTransform {
  transform(list: any[], checked: boolean) {
    if (checked) {
      const futureDates = list.filter(x => {
        return Date.parse(x.bookingEnd) > new Date();
      });
      return futureDates;
    } else {
      return list;
    }
  }
}

bookings-table.component.html:预订表.component.html:

<tr
  *ngFor="
    let item of bookings
    | recentFilter: checked
  ">
      ...
</tr>

Error you get already tells you not to use > to compare dates您得到的错误已经告诉您不要使用 > 来比较日期
To compare them use.getTime() method比较它们使用.getTime() 方法

new Date(x.bookingEnd).getTime() > new Date().getTime()

The problem here seems to be that Date.Parse returns a number.这里的问题似乎是 Date.Parse 返回一个数字。 The documentation says: Date.Parse (Dev Mozilla)文档说: Date.Parse (Dev Mozilla)

You should use new Date(Date.Parse([YOUR_STRING_DATE]));您应该使用new Date(Date.Parse([YOUR_STRING_DATE])); but I would advice you to be aware of wrong string formats and null values will date parsing.但我建议您注意错误的字符串格式,并且 null 值将进行日期解析。

It would be event better to avoid Date.Parse with a more modern syntax for parsing Date Parsing es6 and then compare them using the getTime() function Compare Dates es6最好避免 Date.Parse 使用更现代的语法来解析Date Parsing es6 ,然后使用 getTime() function Compare Dates es6 比较它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM