Cannot read property 'toDate' of undefined when converting firebase timestamp

i get the following output

Timestamp(seconds=1545109200, nanoseconds=0)

i tried doing

{{appoint.appointment_date.toDate() | date}} and i get

TypeError: Cannot read property 'toDate' of undefined

I ultimately want a normal day output like Dec 18, 2018 format

My service

import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { ScheduleService } from '../schedule.service';
import { Schedule } from '../models/schedule.model';

@Component({
  selector: 'app-schedule-list',
  templateUrl: './schedule-list.component.html',
  styleUrls: ['./schedule-list.component.css']
})
export class ScheduleListComponent implements OnInit {
  list:Schedule[];
  constructor(private firestore: AngularFirestore, private service: ScheduleService ) { }

  ngOnInit() {
    this.service.getAppointments().subscribe(actionArray =>{
      this.list = actionArray.map(item =>{
        return{
          ...item.payload.doc.data()
        } as Schedule;
      })
    });
  }

  getSchedules(){
    return this.firestore.collection('schedules').snapshotChanges();
  }

}

Model

export class Schedule {
    name:string;
    appointment_date:any;
}
enter code here

Updated

schedule-list.component

<div class="container ">
    <div class="row">
      <div *ngFor="let appoint of list" class="col-md-8 myCenter mt-2"> 
        <!-- the bottom code should work if items within list exist. -->
        <div class="card">
          <div class="card-header">
              Title: {{appoint.name}}

          </div>
          <div class="card-body">
            <p>{{appoint.appointment_date | date}}</p>
          </div>
      </div>
    </div>
  </div>
</div>

1 answer

  • answered 2018-12-05 21:12 Aragorn

    Without looking at your html, if the appoint maps to the object inside list:Schedule[], then all you need to display date nicely is {{appoint.appointment_date | date}}

    You can format the date in several ways looking here.

    Based on your error, obviously you are getting undefined appointment_date. I'd recheck the logic where you build the list array.

    Consider having appointment_date of type Date:

    export class Schedule {
        name:string;
        appointment_date:Date;
    }