首页 > 解决方案 > 未捕获的错误:无法将“未定义”转换为日期(角度)

问题描述

在此示例中,我想从服务中获取所有预订数据并将它们推送到数组 CalendarEvent[]。但我收到了这个错误Uncaught Error: Unable to convert "undefined" into a date。我认为我的服务有问题?

ng-calendar.component.ts:

export class NgCalendarComponent {
  events: CalendarEvent[] = [];
  bookings: any = {};
  date: string;

  constructor(private bookingService: BookingService) {}

  ngOnInit() {
    this.bookings = this.bookingService.getAllBookings();

    for (let booking of this.bookings) {
      var b = this.bookings[booking];
      this.date = formatDate(b.bookDate, 'medium', 'en-us', 'GMT+8');

      this.events.push({
        start: new Date(this.date),
        title: b.purpose,
      });
    }
  }

预订.service.ts:

export class BookingService {
  constructor(private http: HttpClient) { }

  getAllBookings() {
    return this.http.get('/api/bookings/')
      .pipe(map(response => response));
  }
}

BookingResource.cs:

public class BookingResource
{
    public int Id { get; set; }
    public RoomResource Room { get; set; }
    public KeyValuePairResource Building { get; set; }
    public DateTime BookDate { get; set; }
    public ContactResource Contact { get; set; }
    public string Purpose { get; set; }
    public ICollection<TimeSlotResource> TimeSlots { get; set; }

    public BookingResource()
    {
        TimeSlots = new Collection<TimeSlotResource>();
    }
}

标签: asp.netangulartypescriptangular-calendar

解决方案


getAllBooking()返回一个 observable,你必须订阅它才能得到结果。或将其转换为承诺:

  async getAllBookings() {
    return this.http.get('/api/bookings/').toPromise();
  }

并这样称呼它:

  async ngOnInit() {
    this.bookings = await this.bookingService.getAllBookings();
    ...

推荐阅读