管道日期角度"无法转换"时间戳"

Pac*_*los 4 firebase angular google-cloud-firestore

我正在尝试使用角度管道,具体如下:{{fechaCreacion | date: 'medium'}}我得到以下错误:Unable to convert Timestamp (seconds = 1528157765, nanoseconds = 878000000)" into a date 'for pipe' DatePipe'

这是我在Firestore中的注册: 在此输入图像描述

当我离开时,{{ fechaCreacion }}它显示以下内容:

在此输入图像描述

我怎么解决这个问题?

我正在使用:

Angular 6

"angularfire2":"^ 5.0.0-rc.10"

"firebase":"^ 5.0.4",

component.ts

  aviso: any = {};
  id;
  titulo;
  descripcion;
  fechaCreacion;
  categoria;

  constructor( private fs: FirebaseService, private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.id = this.activatedRoute.snapshot.params['id'];
    this.fs.getAvisoObject(this.id).valueChanges().forEach(aviso => {
      this.titulo= aviso.titulo,
      this.descripcion = aviso.descripcion,
      this.fechaCreacion = aviso.fechaCreacion,
      this.categoria = aviso.categoria
    });
  }
Run Code Online (Sandbox Code Playgroud)

component.html

<mat-card class="px-3 px-md-5 py-3 py-md-4 rounded">
    <div class="row no-gutters small pb-2 mb-3 d-flex justify-content-between border-bottom text-muted">
      <div>
        <span>{{ categoria }}</span>
      </div> 
      <div>
        <span>{{ fechaCreacion | date : 'medium' }}</span>
      </div>
    </div>
    <h2 class="font-weight-bold">{{ titulo }}</h2>
    <h5 class="font-weight-light">{{ descripcion }}</h5>
  </mat-card>
Run Code Online (Sandbox Code Playgroud)

service.ts

getAvisoObject(id: string) {
this.avisoObject = this.afs.doc('avisos/' + id);
return this.avisoObject;
}
Run Code Online (Sandbox Code Playgroud)

Den*_*app 11

您必须调用toDate()将Firebase时间戳转换为管道之前的Javascript Date对象,例如:

{{ creationDate.toDate() | date: 'medium' }}

  • 您可以使用安全的导航运算符:`{{creationDate?.toDate()| date:'medium'}}`(注意`?`符号) (2认同)

Dou*_*son 7

在Firestore中处理时间戳类型数据(即fechaCreacion显示的文档中的字段)时,Firestore客户端库将为您提供一个Timestamp类型对象以响应查询。您需要使用此时间戳来格式化日期以在浏览器中显示。

时间戳以纳秒精度表示时间,其中涉及两个整数,您将在屏幕上看到它们。如果要使用JavaScript Date对象,则可以使用该时间戳上的toDate()方法进行转换,也可以使用将其呈现在屏幕上的任何方法。

  • 我添加了`toDate()`,现在以正确的格式显示日期`{{ fechaCreacion.toDate() | 日期:'中等'}}`。但是我在控制台中收到以下错误:`TypeError: Can not read property 'toDate' of undefined` (3认同)
  • 我已经解决了。我有类型为“Date”的“fechaCreacion”,我将其更改为“any”并且错误消失了。然后就像你的建议`aviso.fechaCreacion.toDate()`。非常感谢您的帮助。 (2认同)