Как правильно загрузить gmail api в приложение angular 2

Я новичок в angular 2, поэтому постараюсь подробно объяснить требование. Приложение, которое я создаю, имеет страницу входа (/login) и страницу настроек (/settings).

когда пользователь получает доступ к странице входа в систему, переменная gapi инициализируется правильно, после чего пользователь входит в приложение.

Как только пользователь входит, у него есть страница настроек. проблема начинается, когда пользователь обновляет страницу, когда это происходит, переменная gapi больше не распознается и становится неопределенной. Я думаю, что библиотека gapi не загружается и, следовательно, не работает.

Я поместил следующий код в файл 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 для обработки описанного выше сценария обновления?

Я пытался работать с решением из Лучший способ дождаться завершения инициализации сторонней JS-библиотеки в службе Angular 2? однако это не сработало, gapi по-прежнему не определен.


person user2145673    schedule 06.04.2017    source источник
comment
Столкнувшись с той же проблемой в Angular 5.xx.   -  person Arpit Kumar    schedule 10.08.2018


Ответы (1)


Что я сделал, так это создал пользовательский GoogleService, который отвечает за инициализацию клиента GAPI в приложениях Angular. Вместо прямого взаимодействия с клиентом 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;
  }
}
person John    schedule 06.07.2020