如何使用JavaScript通过Google Calendar API添加日历活动参会人
错误原因
gapi.client.calendar.events.get返回的是未执行的请求对象,并非活动实际数据,直接修改该对象的attendees属性不会生效- 活动的
attendees字段是存储参会人对象的数组,你直接将其赋值为字符串,会直接覆盖原有列表,触发接口清空原有参会人的逻辑
修正后代码
const addAttendee = (eventId, newAttendeeEmail) => { // 发起获取活动详情的请求,在回调中处理返回的实际活动数据 gapi.client.calendar.events.get({ calendarId: 'primary', eventId: eventId }).execute(existingEvent => { // 兼容无参会人的场景,初始化空数组 const currentAttendees = existingEvent.attendees || []; // 去重校验,避免重复添加同一个邮箱 const alreadyAttendee = currentAttendees.some(item => item.email === newAttendeeEmail); if (!alreadyAttendee) { // 仅在原有数组后追加新参会人,不覆盖原有列表 currentAttendees.push({ email: newAttendeeEmail }); } // 调用patch接口仅更新attendees字段 const patchRequest = gapi.client.calendar.events.patch({ calendarId: 'primary', eventId: eventId, // 可选配置:sendUpdates: 'all' 给所有参会人发送邀请/更新通知 resource: { attendees: currentAttendees } }); patchRequest.execute(updatedEvent => { console.log('更新完成,当前参会人列表:', updatedEvent.attendees); }); }); } // 调用示例 addAttendee('你的活动ID', 'rayen.mechergui@esprit.tn');
补充说明
patch接口支持只传需要更新的字段,不需要提交完整的活动对象,既能提升请求效率,也能避免误改其他字段- 如果你需要给新添加的参会人发送邀请邮件,在
patch请求的参数中添加sendUpdates: 'all'即可
内容的提问来源于stack exchange,提问作者Rayen MECHERGUI
相关产品推荐
相关产品推荐

