无法读取未定义的gapi.client的属性'init'

问题描述 投票:-1回答:1

我正在尝试将Google Calendar API与Js集成到应用程序中。我试图遵循Google Quickstart。如果我将示例代码粘贴到HTML文档中,更改了clientID和API密钥,则在Chrome中打开文件时会收到错误提示。

“无法读取未定义的属性'init'”

同样,使用console.log(gapi.client),我又得到了null

第一个代码块是所有gapi函数所在的位置,第二个代码块是我将api脚本链接到文档的位置(我需要用js来完成)。这两个块位于不同的js文件中。

// Client ID and API key from the Developer Console
    var CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
    var API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

    // Array of API discovery doc URLs for APIs used by the quickstart
    var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];

    // Authorization scopes required by the API; multiple scopes can be
    // included, separated by spaces.
    var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";

    var authorizeButton;
    var signoutButton;
    /**
     *  On load, called to load the auth2 library and API client library.
     */
    function handleClientLoad() {
      gapi.load('client:auth2', initClient());
      console.log(gapi.auth2);
    }

    /**
     *  Initializes the API client library and sets up sign-in state
     *  listeners.
     */
    function initClient() {
      gapi.client.init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES
      }).then(function () {
        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
        console.log(gapi);
        // Handle the initial sign-in state.
        updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
        authorizeButton.onclick = handleAuthClick;
        signoutButton.onclick = handleSignoutClick;
      }, function(error) {
        appendPre(JSON.stringify(error, null, 2));
      });
    }

    /**
     *  Called when the signed in status changes, to update the UI
     *  appropriately. After a sign-in, the API is called.
     */
    function updateSigninStatus(isSignedIn) {
      if (isSignedIn) {
        authorizeButton.style.display = 'none';
        signoutButton.style.display = 'block';
        listUpcomingEvents();
      } else {
        authorizeButton.style.display = 'block';
        signoutButton.style.display = 'none';
      }
    }

    /**
     *  Sign in the user upon button click.
     */
    function handleAuthClick(event) {
      gapi.auth2.getAuthInstance().signIn();
    }

    /**
     *  Sign out the user upon button click.
     */
    function handleSignoutClick(event) {
      gapi.auth2.getAuthInstance().signOut();
    }

    /**
     * Append a pre element to the body containing the given message
     * as its text node. Used to display the results of the API call.
     *
     * @param {string} message Text to be placed in pre element.
     */
    function appendPre(message) {
      var pre = document.getElementById('content');
      var textContent = document.createTextNode(message + '\n');
      pre.appendChild(textContent);
    }

    /**
     * Print the summary and start datetime/date of the next ten events in
     * the authorized user's calendar. If no events are found an
     * appropriate message is printed.
     */
    function listUpcomingEvents() {
      gapi.client.calendar.events.list({
        'calendarId': 'primary',
        'timeMin': (new Date()).toISOString(),
        'showDeleted': false,
        'singleEvents': true,
        'maxResults': 10,
        'orderBy': 'startTime'
      }).then(function(response) {
        var events = response.result.items;
        appendPre('Upcoming events:');

        if (events.length > 0) {
          for (i = 0; i < events.length; i++) {
            var event = events[i];
            var when = event.start.dateTime;
            if (!when) {
              when = event.start.date;
            }
            appendPre(event.summary + ' (' + when + ')')
          }
        } else {
          appendPre('No upcoming events found.');
        }
      });
    }

window.testMicroAppDependency = {
    calendarInit: function(){
        var calendar_root = document.getElementById("gcalendar-root");
        //create authorize button
        var x = document.createElement("button");
        x.setAttribute("id", "authorize_button");
        //x.style = "display: none";
        calendar_root.appendChild(x);
        //create signout button
        x = document.createElement("button");
        x.setAttribute("id", "signout_button");
        //x.style = "display: none";
        calendar_root.appendChild(x);

        authorizeButton = document.getElementById('authorize_button');
        signoutButton = document.getElementById('signout_button');
        
        x = document.createElement("script");
        x.src = "https://apis.google.com/js/api.js";
        x.async = true;
        x.defer = true;
        x.setAttribute("onload", "handleClientLoad()");
        x.setAttribute("onreadystatechange", "if (this.readyState === 'complete') this.onload()");
        calendar_root.appendChild(x);
    }
}

[我是网络开发人员中的新手,也许这是一个愚蠢的问题,或者我不了解Google API的某些知识,但是我无法解决。

感谢您的任何帮助:)

javascript google-calendar-api
1个回答
0
投票

您遇到的主要问题是您在此处将initClient函数作为显式函数进行调用:

gapi.load('client:auth2', initClient())

您必须将其作为隐式函数传递,因为```gapi.load``会将其用作callback(我建议您检查更多有关它们的信息)。因此,必须这样传递:

gapi.load('client:auth2', initClient)

Notice initClient()initClient中括号之间的细微但非常重要的区别。


此外,您还没有设置这些变量,而没有为其分配我可以看到的值:

var authorizeButton;
var signoutButton;

应该为它们分配按钮元素,以便最终在您的代码中对其进行处理:

var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
© www.soinside.com 2019 - 2024. All rights reserved.