Component.html:151 错误错误:InvalidPipeArgument:“无法将“14-05-2021”转换为管道“DatePipe”的日期

时间:2021-05-14 10:13:13

标签: javascript angular typescript date-pipe

我收到后端 LastDate 的回复。我将此绑定到我的 ngModel 并显示在网格中,但在控制台中我收到此错误

enter image description here

这里是对应的代码

<ngx-datatable-column name="Last Date" prop="LastDate">
  <ng-template let-row="row" ngx-datatable-cell-template>
    {{row.LastDate| date: 'dd-MM-yyyy'}}
  </ng-template>
</ngx-datatable-column>

1 个答案:

答案 0 :(得分:1)

日期 (String) "14-05-2021" 会被 Javascript 错误地解释。它接受格式为“MM-DD-YYYY”的日期,而您的输入格式为“DD-MM-YYYY”。快速解决方法是在将字符串发送到 date 管道之前重新格式化字符串。

控制器 (*.ts)

backendFetch().subscribe({
  next: (res: any) => {
    const s = res.LastDate.split("-");
    this.row = {
      ...res,
      LastDate: `${s[1]}-${s[0]}-${s[2]}`;
    }
  },
  error: (error: any) => { }
);

通过这种方式,LastDate 对象的 row 属性被调整为预期的格式“MM-DD-YYYY”。

显然,使用 Array#split 的转换是微不足道的。我相信其他人可以想出更好的解决方案(例如使用 RegEx)。

相关问题