I have tried to connect to the Google Calendar API using Angular 2 so that I can display upcoming events on the web application I am building. I ran through the Google Calendar JavaScript quick-start tutorial and, although everything was in the index.html file, it all worked perfectly. I was able to set up the Google API and place the client ID and API key in my JavaScript code and it properly listed upcoming events from the specified calendar.
Link to the quick-start tutorial: https://developers.google.com/google-apps/calendar/quickstart/js
Once I got the JavaScript tutorial to work, I tried to simply implement the same functionality using Angular2, using components/services rather than just raw JavaScript in a script tag in the index.html file. I am about halfway successful.
The problem: I am getting errors stating "Cannot find name 'gapi'".
When I hit the page that calls the code to load the Google Calendar information for the first time, I get these errors stating that gapi is not defined. gapi exists several places in the code, specifically in services that authenticate and retrieve the event data from the Google Calendar API, respectively. However, if I leave that page and come back, the data will come through without error. I have tried loading the proper script tag in index.html using async, etc., as follows:
<script src="https://apis.google.com/js/client.js?onload=checkAuth" async></script>
How do I solve this problem? My code is very similar to that seen in the repository linked below:
https://github.com/stefanreichert/angular2-google-calendar-example
The problem was trying to retrieve the data from the Google Calendar API before authentication was finished. Using another promise to then load the data after authentication was finished successfully retrieved the event data I was looking for.
Also, it was seemingly helpful to npm install --save @types/gapi, npm install --save @types/gapi.auth2, and declare var gapi: any anywhere I wanted to make calls to gapi in services/components.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With