angularjs - 如何将 gmail api 正确加载到 angular 2 应用程序

标签 angularjs angular typescript gmail-api google-api-js-client

我是 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 仍然是未定义的。

最佳答案

我所做的是创建一个自定义 GoogleService,它负责在 Angular 应用程序中初始化 GAPI 客户端。我的应用不是直接与 GAPI 客户端交互,而是与 GoogleService 交互。

例如(使用 Angular 9.x)

import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';

@Injectable({
  providedIn: 'root',
})
export class GoogleService {
  private gapiAuth?: Promise<gapi.auth2.GoogleAuth>;

  constructor() {
    // Chrome lets us load the SDK on demand, but firefox will block the popup
    // when loaded on demand. If we preload in the constructor,
    // then firefox won't block the popup.
    this.googleSDK();
  }

  async signinGoogle() {
    const authClient = (await this.googleSDK()) as gapi.auth2.GoogleAuth;
    const googleUser = await authClient.signIn();
    const profile = googleUser.getBasicProfile();

    return {
      type: 'GOOGLE',
      token: googleUser.getAuthResponse().id_token as string,
      uid: profile.getId() as string,
      firstName: profile.getGivenName() as string,
      lastName: profile.getFamilyName() as string,
      photoUrl: profile.getImageUrl() as string,
      emailAddress: profile.getEmail() as string,
    };
  }

  async grantOfflineAccess() {
    const authClient: gapi.auth2.GoogleAuth = (await this.googleSDK()) as any;

    try {
      const { code } = await authClient.grantOfflineAccess();

      return code;
    } catch (e) {
      // access was denied
      return null;
    }
  }

  // annoyingly there is some sort of bug with typescript or the `gapi.auth2`
  // typings that seems to prohibit awaiting a promise of type `Promise<gapi.auth2.GoogleAuth>`
  // https://stackoverflow.com/questions/54299128/type-is-referenced-directly-or-indirectly-in-the-fulfillment-callback-of-its-own
  private googleSDK(): Promise<unknown> {
    if (this.gapiAuth) return this.gapiAuth;

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.defer = true;
    script.src = 'https://apis.google.com/js/api.js?onload=gapiClientLoaded';

    this.gapiAuth = new Promise<void>((res, rej) => {
      (window as any)['gapiClientLoaded'] = res;
      script.onerror = rej;
    })
      .then(() => new Promise(res => gapi.load('client:auth2', res)))
      .then(() =>
        gapi.client.init({
          apiKey: environment.google.apiKey,
          clientId: environment.google.clientId,
          discoveryDocs: environment.google.discoveryDocs,
          scope: environment.google.scopes.join(' '),
        }),
      )
      .catch(err => {
        console.error('there was an error initializing the client', err);
        return Promise.reject(err);
      })
      .then(() => gapi.auth2.getAuthInstance());

    document.body.appendChild(script);

    return this.gapiAuth;
  }
}

关于angularjs - 如何将 gmail api 正确加载到 angular 2 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43254549/

相关文章:

javascript - 如何全局访问/抛出 Angular 中的自定义错误?

javascript - 单击子组件而不触发父组件上的单击事件

angular - 如何在 RxJs Observable 构造函数中使用异步调用

javascript - 输入字段修改时运行 $scope 函数?

javascript - D3js 多折线图 mouseOver

angular - 递归地使用组件本身来创建树

typescript - 如何退出 Deno? (process.exit 的模拟)

typescript - Azure函数: Can't figure out which ctor to call

typescript - 在 mac 上构建后在 Electron 应用程序中找不到模块

html - 双括号未在 Angular.js html 中注册