Невозможно прочитать свойство 'init' из неопределенного gapi.client - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь интегрировать API Календаря Google с Js внутри приложения. Я пытался следовать Google Quickstart . Если я вставляю пример кода в HTML do c, меняю clientID и ключ API, я получаю сообщение об ошибке при открытии файла в Chrome.

Кроме того, с console.log(gapi.client) Я получаю обратно null.

Первый блок кода - это место, где вызываются функции gapi (calendar_model. js).

Второй блок - это место, где я связываю скрипт API с документом (мне нужно сделать это js в файле с именем зависимости. js).

Третий блок - это мой индекс. js, откуда я вызываю функцию в зависимости. js.

console.log("first");

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

// 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() {
  console.log("gapi type: " + typeof gapi + '\n');
  console.log("gapi client type: " + typeof gapi.client + '\n');
  gapi.load('client:auth2', initClient);
}

/**
 *  Initializes the API client library and sets up sign-in state
 *  listeners.
 */
function initClient()
{
  console.log("initClient callback start");
  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));
  });
}

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);
    }
}

registry.add("microapp", "googlecalendar", {
        init: function (parentNode, options) {

            this._waitForDependency(function (error, dependency) {
                if (error) {
                    console.error("Unable to start Google Calendar MicroApp: " + error);
                } else {                    
                    var content = document.createElement("div");
                    content.setAttribute("id", "gcalendar-root");
                    parentNode.appendChild(content);
                    dependency.calendarInit();
                }
            });
        },

        _waitForDependency: function(callback) {
            var timeout = 5000;
            var startTime = new Date().getTime();
            var interval = setInterval(function() {
                if (window.hasOwnProperty("testMicroAppDependency")) {
                    clearInterval(interval);
                    callback(null, window.testMicroAppDependency);
                }
                if (new Date().getTime() - startTime > timeout) {
                    clearInterval(interval);
                    callback("Loading of HelloWorld MicroApp scripts timed out.", null);
                }
                console.log("... (waiting for testMicroAppDependency)");
            }, 100);
        }
    });

Вот консоль, где я регистрирую тип gapi и gapi.client. gapi является объектом, поэтому библиотека загружена, но gapi.client не определен. Undefined gapi.client

Я довольно новичок ie в веб-разработчике, возможно, это глупая проблема или я не понял что-то о Google API, но не могу решить это.

Любая помощь приветствуется:)

1 Ответ

0 голосов
/ 10 марта 2020

Основная проблема, с которой вы столкнулись, заключается в том, что вы вызываете функцию initClient как явную функцию здесь:

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

вы должны передать ее как неявную функцию, потому что gapi.load будет использовать ее как обратный вызов (я рекомендую вам проверить больше о них). Следовательно, его нужно передать следующим образом:

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

Обратите внимание на тонкое, но действительно важное различие между круглыми скобками в initClient() и initClient.


Кроме того, у вас есть эти переменные в воздухе, не присваивая им значения для того, что я мог видеть:

var authorizeButton;
var signoutButton;

Им должны быть назначены элементы кнопки, чтобы в конечном итоге обрабатывать их в вашем код:

var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...