在AngularJS应用上开始使用Google API then()函数

时间:2019-05-18 08:59:36

标签: javascript angularjs oauth-2.0 google-api google-oauth

https://github.com/google/google-api-javascript-client/issues/526

我正在按照以下说明开始在angularjs应用程序上使用google api:

https://developers.google.com/calendar/quickstart/js

这是我的尝试:

lib / init.js

function initClient() {
    console.log('-- initClient');
    var resp = gapi.client.init({
        apiKey: '',
        clientId: '',
        discoveryDocs: [
            "https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"
        ],
        scope: [
            'profile',
            'https://www.googleapis.com/auth/calendar.readonly'
        ]
    }).then(function() {
        console.log('-- then') // never executes
       // api loaded
    }, function(error) {
        console.log('ERROR: ' + error);
    });
}

function handleClientLoad() {
    console.log('-- handleClientLoad');
    gapi.load('client:auth2', {
        callback: function() {
            initClient();
        },
        onerror: function() {
            console.log('gapi failed to load!');
        },
        timeout: 5000, // 5 seconds.
        ontimeout: function() {
            // Handle timeout.
            console.log('gapi.client could not load in a timely manner!');
        }
    });
}

index.html

<!doctype html>

<html>
  <head>
    <link rel="stylesheet" href="lib/style.css">
  </head>

  <body ng-app="my-app">
    <div ng-controller="MainCtrl">
        <h3>Testing Google JS API Lib</h3>
    </div>


    <script type="text/javascript" src="lib/init.js"></script>
    <script id="gapiscript" src="https://apis.google.com/js/platform.js?onload=handleClientLoad">
    </script>
    <script src="lib/script.js"></script>
  </body>
</html>

gapi.client.load().then() {...}未执行,并且console.log('-- then')调试行从不显示。做document.getElementbyId('gapiscript')会得到:

<script id="gapiscript" src="https://apis.google.com/…?onload=handleClientLoad" gapi_processed="true">

console.log('-- handleClientLoad');console.log('-- initClient');正在执行并显示在控制台中。我从onerror回调中没有收到错误消息。

我收到的另一个控制台消息是CSI/start cb=gapi.loaded_0:613:127

如何获取then()函数以开始使用api?

1 个答案:

答案 0 :(得分:0)

在我的情况下,gapi.load仅接受单个回调函数:

gapi.load('client:auth2', 
  function() {
    initClient();
  }
);