如何从Firebase JSON获取事件数据到FullCalendar(谷歌Web应用)
解决FullCalendar加载Firebase单条事件数据不显示的问题
核心问题
FullCalendar的events/eventSources要求数据源返回事件对象数组,但你的Firebase URL返回的是单个事件对象(而非数组);同时allDay字段为空字符串,不符合FullCalendar对该字段的布尔值要求,这两点是日历无法渲染事件的关键原因。
修复方案
方案1:调整Firebase数据存储结构
直接在Firebase里把事件存为数组格式,比如将Calendar/Test节点下的数据改为:
[ {"allDay":false,"end":"2023-02-01 18:00:00","id":"EV1","start":"2023-02-05 09:00:00","title":"Event 1"} ]
之后直接使用events: 'https://mydatabase.firebaseio.com/Calendar/Test.json'即可加载,无需额外处理。
方案2:通过FullCalendar回调转换返回数据
如果不想修改Firebase存储结构,可利用eventSources的success回调,将单个对象包装成数组,并修正allDay字段:
const calendarEl = document.getElementById('delivery-calendar') const calendar = new FullCalendar.Calendar(calendarEl, { initialView: 'dayGridMonth', locale: 'th', themeSystem: 'bootstrap5', eventSources: [ { url: 'https://mydatabase.firebaseio.com/Calendar/Test/EV1.json', success: function(response) { // 把单个对象转为数组,同时修正allDay字段为布尔值 const eventArray = [ { ...response, allDay: response.allDay === "" ? false : Boolean(response.allDay) } ]; // 手动添加事件到日历 calendar.addEventSource(eventArray); }, failure: function(error) { console.log('加载事件失败:', error); } } ] }) calendar.render()
注意事项
- 不要用
data函数转换返回数据,data函数的作用是给请求添加URL参数,而非处理响应。 - 确保Firebase数据库规则允许前端读取该节点(测试阶段可临时设置
.read为true,生产环境需配置安全规则)。
内容的提问来源于stack exchange,提问作者Samatcha
相关产品推荐
相关产品推荐

