下面是一个使用Angular和Google Calendar API的代码示例:
npm install --save @types/gapi
npm install --save @types/gapi.auth2
npm install --save @types/gapi.client.calendar
import { Injectable } from '@angular/core';
@Injectable()
export class GoogleAuthService {
private authInstance: gapi.auth2.GoogleAuth;
public loadAuth2(): Promise {
return new Promise((resolve, reject) => {
gapi.load('auth2', () => {
gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID'
}).then((authInstance: gapi.auth2.GoogleAuth) => {
this.authInstance = authInstance;
resolve();
}, (error) => {
reject(error);
});
});
});
}
public signIn(): Promise {
return this.authInstance.signIn();
}
public signOut(): Promise {
return this.authInstance.signOut();
}
public isSignedIn(): boolean {
return this.authInstance.isSignedIn.get();
}
public getCurrentUser(): gapi.auth2.GoogleUser {
return this.authInstance.currentUser.get();
}
}
import { Injectable } from '@angular/core';
import { GoogleAuthService } from './google-auth.service';
@Injectable()
export class GoogleCalendarService {
private calendarApiLoaded: Promise;
constructor(private authService: GoogleAuthService) {
this.calendarApiLoaded = new Promise((resolve, reject) => {
gapi.load('client', () => {
gapi.client.load('calendar', 'v3', () => {
resolve();
});
});
});
}
public getEvents(): Promise {
return this.calendarApiLoaded
.then(() => {
return gapi.client.calendar.events.list({
calendarId: 'primary',
timeMin: (new Date()).toISOString(),
showDeleted: false,
singleEvents: true,
orderBy: 'startTime'
});
})
.then((response) => {
return response.result;
});
}
}
import { Component, OnInit } from '@angular/core';
import { GoogleAuthService } from './google-auth.service';
import { GoogleCalendarService } from './google-calendar.service';
@Component({
selector: 'app-root',
template: `
Upcoming Events:
- {{ event.summary }}
Please sign in to view events
`
})
export class AppComponent implements OnInit {
public isSignedIn: boolean;
public events: gapi.client.calendar.Event[];
constructor(private authService: GoogleAuthService, private calendarService: GoogleCalendarService) {}
public ngOnInit() {
this.isSignedIn = this.authService.isSignedIn();
if (this.isSignedIn) {
this.loadEvents();
}
}
public signIn() {
this.authService.signIn()
.then(() => {
this.isSignedIn = true;
this.loadEvents();
});
}
public signOut() {
this.authService.signOut()
.then(() => {
this.isSignedIn = false;
this.events = [];
});
}
private loadEvents() {
this.calendarService.getEvents()
.then((events) => {
this.events = events.items;
});
}
}
以上代码演示了如何使用Angular和Google Calendar API进行身份验证并获取用户的日历事件。请确保替换YOUR_CLIENT_ID为您的Google API客户端ID。