如何正确加载gmail api到angular 2 app

时间:2017-04-06 11:57:13

标签: angularjs angular typescript gmail-api gapi

我对棱角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仍未定义。

1 个答案:

答案 0 :(得分:0)

我所做的是创建一个自定义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;
  }
}