How to Integrate Third-Party SDK into Angular App
Most widely-used APIs provide comprehensive guides for JavaScript integration into web applications. However, adapting these integrations to Angular can sometimes present challenges. In this article, we’ll explore the integration of the Google Calendar API into an Angular application, providing a step-by-step guide for seamless implementation. While the process may involve several components, this article will serve as a concise reference.
Introduction
Integrating APIs into web applications is a common practice, yet when it comes to incorporating them into Angular applications, the process can become more intricate. As an illustrative example, we’ll delve into the integration of the Google Calendar API within an Angular context. Although obtaining Google API credentials is a prerequisite (covered in the official JS guide), this article will focus on the integration process itself, specifically emphasizing the dynamic loading of the Google API SDK.
Dynamic Loading of Google API SDK
The foundation of our implementation involves creating a custom module to load two essential SDK links before rendering a designated component. The following URLs are crucial for the integration process:
const GOOGLE_CALENDAR_GAPI_SDK = 'https://apis.google.com/js/api.js';
const GOOGLE_CALENDAR_GIS_SDK = 'https://accounts.google.com/gsi/client';To facilitate the dynamic loading, we establish functions for injecting scripts onto the page:
// google-factory.ts
import { InjectionToken } from '@angular/core';
const CLIENT_ID = '708353567948-kq391iebelqkndr0hir8qijbqtpts3mf.apps.googleusercontent.com';
const API_KEY = 'AIzaSyBEE3-D31HShcqmAdFLbJETznBteI-9xEo';
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest';
const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';
export const GOOGLE_CALENDAR_GAPI_INSTANCE = new InjectionToken<Promise<any>>('google.calendar.gapi.instance');
export const GOOGLE_CALENDAR_GIS_INSTANCE = new InjectionToken<Promise<any>>('google.calendar.gis.instance');
const GOOGLE_CALENDAR_GAPI_SDK = 'https://apis.google.com/js/api.js';
const GOOGLE_CALENDAR_GIS_SDK = 'https://accounts.google.com/gsi/client';
declare let google: any;
declare let gapi: any;
export function getGapi(): any {
if (window && (window as any)?.gapi) {
gapi.load('client', initializeGapiClient);
return window && (window as any).gapi;
}
return false;
}
export function getGis(): any {
if (window && (window as any).google) {
gisLoaded();
return window && (window as any).google;
}
return false;
}
export function loadGapiSdk(): Promise<any> {
const gapi = getGapi();
return gapi ? Promise.resolve( gapi ) : new Promise( (resolve, reject) => {
try {
const findGapiScript = () => document.querySelector<HTMLScriptElement>(`script[src^="${GOOGLE_CALENDAR_GAPI_SDK}"]`);
const injectGapiScript = () => {
const script = document.createElement('script');
script.src = GOOGLE_CALENDAR_GAPI_SDK;
script.type = 'text/javascript';
script.defer = true;
script.async = true;
(document.head || document.body).appendChild(script);
return script;
};
const gapiScript = findGapiScript() || injectGapiScript();
gapiScript.addEventListener('error', () => reject( new Error("Unable to load") ));
gapiScript.addEventListener('load', () => resolve( getGapi() ));
}
catch(e) { reject(e); }
});
}
export function loadGisSdk(): Promise<any> {
const gis = getGis();
return gis ? Promise.resolve( gis ) : new Promise( (resolve, reject) => {
try {
const findScript = () => document.querySelector<HTMLScriptElement>(`script[src^="${GOOGLE_CALENDAR_GIS_SDK}"]`);
const injectScript = () => {
const script = document.createElement('script');
script.src = GOOGLE_CALENDAR_GIS_SDK;
script.type = 'text/javascript';
script.defer = true;
script.async = true;
(document.head || document.body).appendChild(script);
return script;
};
const gisScript = findScript() || injectScript();
gisScript.addEventListener('error', () => reject( new Error("Unable to load SDK") ));
gisScript.addEventListener('load', () => resolve( getGis() ));
}
catch(e) { reject(e); }
});
}
export async function initializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
}
export function gisLoaded() {
return google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '',
});
}The code above provides utility functions and structures to load the required SDKs, initialize the Google Calendar API client, and set up the Google Identity Services for authentication within an Angular application. The use of promises and asynchronous functions ensures that these operations are performed in a non-blocking manner, enhancing the application’s performance and user experience. Here’s a breakdown of the code:
- Injection Tokens: The code creates two
InjectionTokeninstances namedGOOGLE_CALENDAR_GAPI_INSTANCEandGOOGLE_CALENDAR_GIS_INSTANCE. These tokens are used to provide instances of the Google Calendar API and Google Identity Services through dependency injection in Angular. - Global Declarations: It uses the
declarekeyword to let TypeScript know about the global variablesgoogleandgapi, which are expected to be available through the Google SDKs. getGapi()andgetGis()Functions: These functions are used to check whether thegapiandgoogleobjects are available in the global scope. If available, the associated SDKs are initialized, and the corresponding object is returned. Otherwise, it returnsfalse.- Google SDK URLs: The code defines URLs for the Google API and Google Identity Services SDKs.
loadGapiSdk()andloadGisSdk()Functions: These functions are responsible for dynamically loading the Google API and Google Identity Services SDKs if they are not already loaded. They return promises that resolve to the respective SDK objects.initializeGapiClient()Function: This asynchronous function initializes the Google Calendar API client using thegapi.client.initmethod. It requires the API key and the discovery document URL.gisLoaded()Function: This function initializes the Google Identity Services token client for authentication. It is called once the Google Identity Services SDK is loaded.
Creating the NgModule
The NgModule acts as a pivotal element in our implementation, encompassing component declarations, exports, and provider configurations. Its purpose is to facilitate the loading of Google API instances via factory functions:
import {NgModule} from '@angular/core';
import {
GOOGLE_CALENDAR_GAPI_INSTANCE,
GOOGLE_CALENDAR_GIS_INSTANCE,
loadGapiSdk,
loadGisSdk
} from './google-factory';
import {GoogleCalendarComponent} from '../google-calendar.component';
@NgModule({
declarations: [ GoogleCalendarComponent ],
exports: [ GoogleCalendarComponent],
providers: [
{
provide: GOOGLE_CALENDAR_GAPI_INSTANCE,
useFactory: loadGapiSdk
},
{
provide: GOOGLE_CALENDAR_GIS_INSTANCE,
useFactory: loadGisSdk
},
],
})
export class GoogleCalendarModule {}If you want to import the NgModule you can find a solution in this article:
Developing the Angular Component
The heart of our implementation resides in the GoogleCalendarComponent. This Angular component authenticates with the Google Calendar API, seeks user consent, and retrieves and displays forthcoming events from the user’s primary calendar. Let’s delve into its key elements:
import {Component, Inject, OnInit} from '@angular/core';
import {GOOGLE_CALENDAR_GAPI_INSTANCE, GOOGLE_CALENDAR_GIS_INSTANCE} from "./google/google-factory";
const CLIENT_ID = '708353567948-kq391iebelqkndr0hir8qijbqtpts3mf.apps.googleusercontent.com';
const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';
declare const google: any;
declare const gapi: any;
@Component({
selector: 'app-google-calendar',
templateUrl: './google-calendar.component.html',
styleUrls: ['./google-calendar.component.scss'],
})
export class GoogleCalendarComponent{
tokenClient: any;
constructor(@Inject(GOOGLE_CALENDAR_GAPI_INSTANCE) private gapiInstance: Promise<any>,
@Inject(GOOGLE_CALENDAR_GIS_INSTANCE) private gisInstance: Promise<any>) {
}
handleAuth() {
this.tokenClient = (window as any).google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: {}, // defined later
});
this.tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('authorize_button').innerText = 'Refresh';
await this.listUpcomingEvents();
};
if ((window as any).gapi.client.getToken() === null) {
this.tokenClient.requestAccessToken({prompt: 'consent'});
} else {
this.tokenClient.requestAccessToken({prompt: ''});
}
}
async listUpcomingEvents() {
let response;
const request = {
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime',
};
response = await gapi.client.calendar.events.list(request);
const events = response.result.items;
if (!events || events.length == 0) {
return;
}
const output = events.reduce(
(str, event) => `${str}${event.summary} (${event.start.dateTime || event.start.date})\n`,
'Events:\n');
console.log('listUpcomingEvents output', output);
}
}Here’s a description of the component’s code:
- Constants
CLIENT_IDandSCOPESdefine the client ID and scopes required for accessing the Google Calendar API. - The
declarestatements inform TypeScript about the existence of external global variablesgoogleandgapi, which are likely part of the Google API SDK. - Inside the component class, a property
tokenClientis declared to store the OAuth2 token client instance. - The constructor takes two dependencies,
gapiInstanceandgisInstance, injected using the@Injectdecorator with corresponding tokens (GOOGLE_CALENDAR_GAPI_INSTANCEandGOOGLE_CALENDAR_GIS_INSTANCE). - The
handleAuthmethod is defined to initiate the authentication process. It initializes thetokenClientusinggoogle.accounts.oauth2.initTokenClient, and sets up a callback function to handle the response. The method also checks if the user is already authenticated (getToken() === null) and prompts for consent if needed. - The
listUpcomingEventsmethod fetches upcoming events from the user's primary calendar. It constructs a request object and uses thegapi.client.calendar.events.listmethod to retrieve the events. The results are processed, and event summaries along with start times are logged to the console.
Conclusion
Incorporating APIs into Angular applications necessitates a nuanced approach due to the framework’s architecture. By demonstrating the integration of the Google Calendar API, we’ve showcased a structured methodology for overcoming these challenges. This article has explored dynamic SDK loading, injection tokens for SDK instances, and the creation of a dedicated NgModule. The resultant Angular component effectively interacts with the Google Calendar API, demonstrating the potential of harmonizing external APIs with Angular’s ecosystem.
By adapting this approach, developers can navigate the integration of various APIs within Angular applications, fostering a more seamless user experience while harnessing the capabilities of external services.
Thanks for your attention, if you like this article you can 👏 , follow me, or write a comment. You can also see my previous articles: