首页 > 解决方案 > 如何使用 NgOnChanges 更新 FullCalendar 上的事件?

问题描述

我正在开发 Angular 7 上的预订房间应用程序。

我正在使用完整的日历来显示数据库中的事件。

FullCalendar 对一个房间运行良好,但每次我从另一个房间切换时,它都会初始化另一个日历。

我的代码看起来像这样。

 ngOnChanges(changes: any) {

    this.getAllReservations();
    
  }

public getAllReservations() {

    let apiUrl: string = `api/Reservations/Room=${this.selection}`;
    this.repository.getData(apiUrl).subscribe(res => {
      this.Reservations = res as Reservation[];

      //full calendar intit
      var calendarEl = document.getElementById('calendar');
      var calendar = new Calendar(calendarEl, {
        
        events: this.Reservations.map(function (x) { 
          return {
            title: x.Note,
            start: x.StartDate,
            end: x.EndDate
          };
        }),
      });     
      calendar.render();
      },
      (error) => {
        this.errorHandler.handleError(error);
        this.errorMessage = this.errorHandler.errorMessage;
      })
  }

我重复一遍,这段代码运行良好,我得到了我的事件。=> 证明

但这每次我打电话给房间时都会在下面创建一个新日历,这是我的问题。

我完全明白了,但我找不到解决我的问题的解决方案。我试图在 ngOnInit 中隔离日历并只更新事件,但函数事件没有找到日历。

标签: javascriptangulareventsfullcalendar

解决方案


好的 Christophe Sacchi,如果我假设您只使用您的 api 预订一个房间,这是正常的。您应该汇总每个房间的所有预订:

public getAllReservations() {
  this.Reservations = [];
  rooms.map(room => {
    const apiUrl: string = `api/Reservations/Room=${room}`;
    const roomReservations = this.repository.getData(apiUrl).subscribe(res => res as Reservation[],
      (error) => {
        this.errorHandler.handleError(error);
        this.errorMessage = this.errorHandler.errorMessage;
      });
    this.Reservations.push(roomReservations);
  });

  //full calendar intit
  const calendarEl = document.getElementById('calendar');
  const calendar = new Calendar(calendarEl, {
    events: this.Reservations.map(roomReservations => roomReservations.map(reservation => ({
        title: reservation.Note,
        start: reservation.StartDate,
        end: reservation.EndDate
      })),
    ),
  });
  calendar.render();
}

如果你尝试这样的事情(在没有测试的情况下内联完成,所以你可能需要稍微更新一下),它有效吗?

抱歉,我不是 Angular 开发人员。


推荐阅读