如何从PrimeNG FullCalendar中动态删除事件(点击事件)?

问题描述 投票:-2回答:1

我正在使用PrimeNG Full Calendar组件制作一个Angular应用,这个组件。https:/primefaces.orgprimengshowcase#fullcalendar。

那是基于Angular FullCalendar组件,这个。https:/fullcalendar.io

在这里你可以找到我的全部代码。https:/bitbucket.orgdgs_poste_teamsoc_calendarsrcmaster。

所以我有一个这样的日历。

enter image description here

现阶段我想实现的是,当用户点击一个特定的事件时,所有进入这个日历的事件都将被删除(在第二阶段,我将实现只有被点击的特定事件才会被删除,但目前我尽量保持逻辑简单)。

所以这就是控制我的日历组件的类。

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { EventService } from '../event.service';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import listPlugin from '@fullcalendar/list';
import interactionPlugin, { Draggable } from '@fullcalendar/interaction';
import { FullCalendar } from 'primeng';

@Component({
  selector: 'app-fullcalendar',
  templateUrl: './fullcalendar.component.html',
  styleUrls: ['./fullcalendar.component.css']
})
export class FullcalendarComponent implements OnInit {

  events: any[];
  options: any;
  header: any;

  //people: any[];

  @ViewChild('fullcalendar') fullcalendar: FullCalendar;

  calendar:any;


  constructor(private eventService: EventService) {}

  ngOnInit() {
    //this.eventService.getEvents().then(events => { this.events = events;});

    this.eventService.getEvents().subscribe(events => { this.events = events.map((event) => {
      var date = new Date(event.start);
      var hour = date.getHours();
      //event['backgroundColor'] = hour === 7? 'red': (hour === 7 ? 'green' : 'black');

      //let events = this.calendar.getEvents();
      //events[

      console.log("EVENTS: " + this.events);

      if(hour === 7) {
        event['backgroundColor'] = 'red';
      }
      else if(hour === 15) {
        event['backgroundColor'] = 'green';
      }
      else if(hour === 23) {
        event['backgroundColor'] = 'black';
      }


      return event;
    })});

    this.options = {
        plugins:[ dayGridPlugin, timeGridPlugin, interactionPlugin, listPlugin ],
        defaultDate: '2017-02-01',
        header: {
            left: 'prev,next',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        editable: true,
        nextDayThreshold: '09:00:00',
        allDayDefault: false,

        dateClick: (dateClickEvent) =>  {         // <-- add the callback here as one of the properties of `options`
          console.log("DATE CLICKED !!!");
        },

        eventClick: (eventClickEvent) => {
          console.log("EVENT CLICKED !!!");
          console.log(eventClickEvent.event.id);
          //this.eventService.removeEventById(eventClickEvent.event.id);
          this.eventService.removeEventById(eventClickEvent.event.id).subscribe(events => console.log(events));


            /*
            events => { this.events = events.map((event) => {
            var date = new Date(event.start);
            var hour = date.getHours();

            console.log("EVENTS: " + this.events);

            if(hour === 7) {
              event['backgroundColor'] = 'red';
            }
            else if(hour === 15) {
              event['backgroundColor'] = 'green';
            }
            else if(hour === 23) {
              event['backgroundColor'] = 'black';
            }

            return event;
          })});
          */
        },

        eventDragStop: (eventDragStopEvent) => {
          console.log("EVENT DRAG STOP !!!");
        },

        eventReceive: (eventReceiveEvent) => {
          console.log(eventReceiveEvent);
          //eventReceiveEvent.event.setAllDay(false, {maintainDuration: true});



          //eventReceiveEvent['backgroundColor'] = 'red';
          this.eventService.addEvent(eventReceiveEvent);
        }
    };

  }

  ngAfterViewInit() {

    this.calendar = this.fullcalendar.getCalendar();
    console.log("CALENDAR: " + this.calendar);

  }

}

你可以看到进入 ngOnInit() 方法,我订阅了 getEvents() 方法,以Observable的形式返回已渲染的事件列表(我这样做是因为在返回的输出中,我处理了不同事件类型的不同颜色,但这与我的问题没有严格的关系......它工作得很好)。

所以,如你所见,这个组件类包含了这个钩子方法 事件点击。(eventClickEvent) 处理点击我的日历上的一个事件。我想调用一个定义到我的服务中的删除事件方法,然后再重新渲染,但这是行不通的(我已经做了几次尝试,但还是行不通)。我也不确定这是解决问题的正确方法。

从我了解到的 ngOnInit() 方法,我有订阅我的日历事件数组,所以链这个数组的内容的变化发布,它应该再次呈现,我也试过,但它是不工作的......所以我认为,可能是我在Angular逻辑遗漏的东西。

这是我服务类的代码。

import { Injectable } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class EventService {

  private events = [];

  /*
  private events = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 3, title: 'test', start: '2017-02-20T07:00:00'},
  ];
  */

  private people = [
    {id: 1, name: "PERSONA 1"},
    {id: 2, name: "PERSONA 2"},
    {id: 3, name: "PERSONA 3"},
    {id: 4, name: "PERSONA 4"},
    {id: 5, name: "PERSONA 5"},
  ]

  public eventData = new BehaviorSubject(this.events);

  constructor(private http: HttpClient) {}

  getEvents(): Observable<any[]> {
    return this.eventData.asObservable();
  }


  addEvent(event) {
    //console.log(event.event.start);
    //console.log(event);
    const newEvent = {id: 5, title: event.event.title, start: event.event.start, end: event.event.end};
    this.events.push(newEvent);
    this.eventData.next([...this.events]);
    //console.log(this.events);
  }

  removeEventById(id:number): Observable<any[]>  {
    console.log("EVENTDATA: " + this.eventData.getValue());

    return this.eventData.asObservable();
  }


  /*
  removeEventById = (id:number) => {
    this.events = [];
    //return this.events.filter(each=>each.id!=id);

  }
  */

  getPeople(): Promise<any[]> {
    return Promise.all(this.people)
        .then(res => {
          console.log(res);
          return res;
        })
  }

}

那到底是哪里出了问题?我遗漏了什么?有什么聪明的办法可以正确处理我的问题?

angular fullcalendar primeng
1个回答
0
投票

所以有你几件事应该到位。

  1. 对于删除所有事件。

    在events.service中

public deleteEvents() {
   this.events = [];
   this.eventData.next(this.events);
 }

fullCalendar.component.ts fullCalendar选项:-

eventClick: (eventClickEvent) => {
      console.log("EVENT CLICKED !!!");
      this.eventService.deleteEvents();
    }
  1. 用于删除特定事件。

首先,在你的日历中,每个事件都应该有一个唯一的ID。目前在你的addEvent方法中,你给每个事件提供了相同的ID,即5。

public currentId = 1;

public addEvent() {
      const newEvent = {id: this.currentId++, title: event.event.title, start: event.event.start, end: event.event.end};
   //Remaining Add Event Code.
}

这样一来,每当事件被添加到你的日历时,你就会有一个唯一的ID。

现在,当事件被点击时,你会调用一个方法,即 removeEventById()。应该写成:-

removeEventById(id): Observable<any[]>  {
    this.events = this.events.filter((event) => event.id!==+id);
    this.eventData.next(this.events);
    return this.eventData.asObservable();
}

注意:-你从事件点击对象中接收到的id是字符串,而你在数组中的id是数字。因此,我在接收到的id中加入了+,以便在数字中解析出与id相匹配的id,并删除必要的项目。

fullCalendar.component.ts fullCalendar选项:-

eventClick: (eventClickEvent) => {
      console.log("EVENT CLICKED !!!");        
 this.eventService.removeEventById(eventClickEvent.event.id).subscribe(events => console.log(events));
    }

7
投票

primeng fullcalendar是由fullcalendar.io开发的,你可以过滤数据,然后分配给eventData。我把你的代码创建在 演示

 this.eventService.removeEventById(eventClickEvent.event.id).subscribe(events => console.log(events));

在你的方法中

removeEventById(id:number): Observable<any[]>  {
    this.events=this.events.filter(each=>each.id!=id);
    this.eventData.next([...this.events]);
    return this.eventData.asObservable();
}

1
投票

由于您使用的是 Observables,您可以使用 map 经营者与 Array.prototype.filter:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

removeEventById(id:number): Observable<any[]>  {    
    return this.getEvents()
        .pipe(
            map(items => items.filter(item => item.id == id))
        );    
} 

整个工作实例可以在stackblitz上看到。

所以你的服务可以是这样的。

@Injectable()
export class MyServices {
    private events = [
        {   
          id: 1,
          title: 'Foo 1',
          date: '2020-06-07'
        },
        {
          id: 2,
          title: 'Foo 2',
          date: '2020-06-08'
        },
        {
          id: 3,
          title: 'Foo 3',
          date: '2020-06-05'
        }
    ];

    public eventData = new BehaviorSubject(this.events);

    constructor() { }

    sayHello() {        
        console.log("Say Hello");
    }

    getEvents(): Observable<any[]> {
        return this.eventData.asObservable();
    }


  addEvent(event) {
    const newEvent = {id: 5, title: event.event.title, 
        start: event.event.start, end: event.event.end};
    this.events.push(newEvent);
    this.eventData.next(Object.assign({}, this.events));
  }

  removeEventById(id:number): Observable<any[]>  {    
    return this.getEvents()
      .pipe(
        map(items => items.filter(item => item.id == id))
      );    
  }    
}

and your.component.ts 可能是这样的。

export class AppComponent implements OnInit {
    options: any;
    eventsModel: any;
    @ViewChild('fullcalendar') fullcalendar: FullCalendarComponent;
    @ViewChild('external') external: ElementRef;

    constructor(private myServices: MyServices){
        this.myServices.sayHello();
    }

    eventClick(model) {
        this.myServices.removeEventById(model.id)
            .subscribe(s => this.eventsModel = s);       
    }
© www.soinside.com 2019 - 2024. All rights reserved.