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