#angular #typescript #google-calendar-api
Вопрос:
Я пытаюсь добавить встречу в свой календарь Google, я могу загрузить данные из календаря через событие прослушивания, но когда я пытаюсь создать новые данные для добавления в календарь, это выдает ошибку. Что я делаю не так?
import { Component, NgZone, OnInit, ViewChild } from '@angular/core';
import { CalendarOptions } from '@fullcalendar/angular';
import { Prenotazioni2 } from 'src/models/data.models';
import { PrenotazioniService } from 'src/app/services/prenotazioni.service';
import { MbscEventcalendarOptions, MbscDatepickerOptions, MbscPopup, MbscPopupOptions, Notifications, MbscEventcalendarView, MbscCalendarEvent, setOptions } from '@mobiscroll/angular';
setOptions({
theme: 'ios',
themeVariant: 'light'
});
// This is for testing purposes. Please use your own API KEY. You can get it from https://developers.google.com/calendar/quickstart/js
const API_KEY = 'xxx';
// This is for testing purposes. Please use your own CLIENT ID. You can get it from https://developers.google.com/calendar/quickstart/js
const CLIENT_ID = 'xxx-xxx.apps.googleusercontent.com';
const CALENDAR_ID = 'xxx.xxx@gmail.com';
const DISCOVERY_DOCS = ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'];
const SCOPES = 'https://www.googleapis.com/auth/calendar';
const win: any = window;
const now = new Date();
let calApiLoaded: boolean;
@Component({
selector: 'app-calendario-aula-blu',
templateUrl: './calendario-aula-blu.component.html',
styleUrls: ['./calendario-aula-blu.component.css']
})
export class CalendarioAulaBluComponent implements OnInit {
public prenotazioni: Prenotazioni2[]
firstDay: Date = new Date(now.getFullYear(), now.getMonth() - 1, -7);
lastDay: Date = new Date(now.getFullYear(), now.getMonth() 2, 14);
view = 'month';
calView: MbscEventcalendarView = {
calendar: { labels: true }
};
calSettings: MbscEventcalendarOptions = {
onPageLoading: (event: any) => {
const start = event.month ? event.month : event.firstDay;
const year = start.getFullYear();
const month = start.getMonth();
// Calculate dates
// (pre-load events for previous and next months as well)
this.firstDay = new Date(year, month - 1, -7);
this.lastDay = new Date(year, month 2, 14);
this.loadEvents(this.firstDay, this.lastDay);
this.saveEvent();
}
};
myEvents: MbscCalendarEvent[] = [];
// Init the Google API client
initClient = () => {
win.gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(() => {
calApiLoaded = true;
this.loadEvents(this.firstDay, this.lastDay);
});
}
constructor(private notify: Notifications, private prenotazioniService: PrenotazioniService, public zone: NgZone) { }
@ViewChild('popup', { static: false })
popup!: MbscPopup;
popupEventTitle: string | undefined;
popupEventDescription = '';
popupEventAllDay = true;
popupEventDates: any;
popupEventStatus = 'busy';
calendarSelectedDate: any = now;
switchLabel: any = 'All-day';
ngOnInit(): void {
this.getEntries();
// Load the Google API Client
win.onGoogleLoad = () => {
win.gapi.load('client', this.initClient);
};
this.loadGoogleSDK();
}
//Funzione per caricare tutte le prenotazioni dell'aula blu nel calendario
getEntries() {
this.prenotazioniService.getData().subscribe((response: any) => {
this.prenotazioni = response;
})
}
// Load the SDK asynchronously
loadGoogleSDK(): void {
((d: any, s: any, id: any) => {
let js: any;
const fjs: any = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
win.onGoogleLoad();
return;
}
js = d.createElement(s);
js.id = id;
js.src = 'https://apis.google.com/js/api.js?onload=onGoogleLoad';
js.onload = 'onGoogleLoad';
fjs.parentNode.insertBefore(js, fjs);
})(document, 'script', 'google-jssdk');
}
// Load events from Google Calendar between 2 dates
loadEvents(first: Date, last: Date): void {
// Only load events if the Google API finished loading
if (calApiLoaded) {
win.gapi.client.calendar.events.list({
calendarId: CALENDAR_ID,
timeMin: first.toISOString(),
timeMax: last.toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 100,
orderBy: 'startTime'
}).then((response: any) => {
let event;
const events = response.result.items;
const eventList: MbscCalendarEvent[] = [];
let end;
// Process event list
for (const value of events) {
event = value;
end = new Date(event.end.date || event.end.dateTime);
eventList.push({
start: new Date(event.start.date || event.start.dateTime),
end: event.end.date ? new Date(end.getFullYear(), end.getMonth(), end.getDate() - 1) : end,
title: event.summary || 'No Title',
allDay: !event.start.dateTime
});
}
this.zone.run(() => {
// Pass the processed events to the calendar
this.myEvents = eventList;
});
});
}
}
changeView(): void {
setTimeout(() => {
switch (this.view) {
case 'month':
this.calView = {
calendar: { labels: true },
};
break;
case 'week':
this.calView = {
schedule: { type: 'week' }
};
break;
case 'day':
this.calView = {
schedule: { type: 'day' }
};
break;
case 'agenda':
this.calView = {
calendar: { type: 'week' },
agenda: { type: 'week' }
};
break;
}
});
}
tempEvent!: MbscCalendarEvent;
calendarOptions: MbscEventcalendarOptions = {
clickToCreate: 'double',
dragToCreate: true,
dragToMove: true,
dragToResize: true,
view: {
calendar: { type: 'month', labels: true }
},
onEventClick: (args) => {
this.isEdit = true;
this.tempEvent = args.event;
// fill popup form with event data
this.loadPopupForm(args.event);
// set popup options
this.popupHeaderText = 'Edit event';
this.popupButtons = this.popupEditButtons;
this.popupAnchor = args.domEvent.currentTarget;
// open the popup
this.popup.open();
},
onEventCreated: (args) => {
setTimeout(() => {
this.isEdit = false;
this.tempEvent = args.event;
// fill popup form with event data
this.loadPopupForm(args.event);
// set popup options
this.popupHeaderText = 'New Event';
this.popupButtons = this.popupAddButtons;
this.popupAnchor = args.target;
// open the popup
this.popup.open();
});
},
onEventDeleted: (args) => {
setTimeout(() => {
this.deleteEvent(args.event);
});
},
onEventUpdated: (args) => {
// here you can update the event in your storage as well, after drag amp; drop or resize
// ...
}
};
popupHeaderText!: string;
popupAnchor: HTMLElement | undefined;
popupAddButtons = ['cancel', {
handler: () => {
this.saveEvent();
},
keyCode: 'enter',
text: 'Add',
cssClass: 'mbsc-popup-button-primary'
}];
popupEditButtons = ['cancel', {
handler: () => {
this.saveEvent();
},
keyCode: 'enter',
text: 'Save',
cssClass: 'mbsc-popup-button-primary'
}];
popupButtons: any = [];
popupOptions: MbscPopupOptions = {
display: 'bottom',
contentPadding: false,
fullScreen: true,
onClose: () => {
if (!this.isEdit) {
// refresh the list, if add popup was canceled, to remove the temporary event
this.myEvents = [...this.myEvents];
}
},
responsive: {
medium: {
display: 'anchored',
width: 400,
fullScreen: false,
touchUi: false
}
}
};
datePickerControls = ['date'];
datePickerResponsive: any = {
medium: {
controls: ['calendar'],
touchUi: false
}
};
datetimePickerControls = ['datetime'];
datetimePickerResponsive = {
medium: {
controls: ['calendar', 'time'],
touchUi: false
}
};
datePickerOptions: MbscDatepickerOptions = {
select: 'range',
showRangeLabels: false,
touchUi: true
};
isEdit = false;
loadPopupForm(event: MbscCalendarEvent): void {
this.popupEventTitle = event.title;
this.popupEventDescription = event.description;
this.popupEventDates = [event.start, event.end];
this.popupEventAllDay = event.allDay || false;
this.popupEventStatus = event.status || 'busy';
}
saveEvent(): void {
this.tempEvent.title = this.popupEventTitle;
this.tempEvent.description = this.popupEventDescription;
this.tempEvent.start = this.popupEventDates[0];
this.tempEvent.end = this.popupEventDates[1];
this.tempEvent.allDay = this.popupEventAllDay;
this.tempEvent.status = this.popupEventStatus;
if (this.isEdit) {
// update the event in the list
var request = win.gapi.client.calendar.events.insert({
'calendarId': CALENDAR_ID,
'resource': this.tempEvent
});
this.myEvents = [...this.myEvents];
} else {
this.myEvents = [...this.myEvents, this.tempEvent];
}
// navigate the calendar
this.calendarSelectedDate = this.popupEventDates[0];
// close the popup
this.popup.close();
}
deleteEvent(event: MbscCalendarEvent): void {
this.myEvents = this.myEvents.filter(item => item.id !== event.id);
this.notify.snackbar({
button: {
action: () => {
this.myEvents = [...this.myEvents, event];
},
text: 'Undo'
},
message: 'Event deleted'
});
// here you can delete the event from your storage as well
// ...
}
onDeleteClick(): void {
this.deleteEvent(this.tempEvent);
this.popup.close();
}
}
Я не понимаю, почему это не заставляет меня создавать событие в календаре Google
Комментарии:
1. это дает мне ошибку , какую ошибку?
2. по правде говоря, это не дает мне никакой ошибки. это не добавляет новое событие