【发布时间】:2017-09-01 10:43:28
【问题描述】:
我对 Angular 2 有点陌生,所以我会尝试详细解释这个要求。 我构建的应用程序有一个登录页面 (/login) 和设置页面 (/settings)。
当用户访问登录页面时,gapi var 被正确初始化,然后用户登录到应用程序。
一旦用户进入,他就有了设置页面。当用户刷新页面时,问题就开始了,当这种情况发生时,gapi var 不再被识别并变得未定义。我的想法是 gapi 库没有被加载,因此它失败了。
我在app index.html文件中放了如下代码
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '***.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
console.log("handleClientLoad")
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
console.log("client init");
gapi.auth2.getAuthInstance().isSignedIn.listen();
// Handle the initial sign-in state.
//updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload=this.onload=function(){};handleClientLoad();
onreadystatechange="if (this.readyState === 'complete') this.onload()";>
</script>
总结一下如何正确加载gapi模块来处理上述刷新场景?
我尝试使用来自 Best way to wait for 3rd-party JS library to finish initializing within Angular 2 service? 的解决方案,但没有成功,gapi 仍然未定义。
【问题讨论】:
-
在 Angular 5.xx 中面临同样的问题。
标签: angularjs angular typescript gmail-api google-api-js-client