API Google Диска в Angular2/Ionic2 gapi.client.drive

Я пишу приложение Angular2/Ionic2, чтобы показать список и загрузить файл на Google Диск. Вход через Google работает нормально, но gapi.client.drive не определено. Что мне делать, чтобы решить эту проблему или вместо этого использовать метод?

я установил

npm install --save @types/gapi

npm install --save @types/gapi.auth2

И мой код home.ts

import { Component, NgZone } from '@angular/core';

import { NavController } from 'ionic-angular';

import { Http, Headers } from '@angular/http';

import { DriveService } from '../../services/drive.service';



@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [ DriveService ]
})
export class HomePage {
  googleLoginButtonId = "google-login-button";
  userAuthToken = null;
  userDisplayName = "empty";
    auth2: any;

  constructor(public navCtrl: NavController, private _zone: NgZone, private driveService: DriveService) {

  }


  start() {
    gapi.load('auth2', () => {
      // Retrieve the singleton for the GoogleAuth library and set up the client.
       this.auth2 = gapi.auth2.init({
        client_id: 'xxx.googleusercontent.com',
        scope: 'https://www.googleapis.com/auth/drive'
      });
      this.attachSignin(document.getElementById('customBtn'));
    });
  };

  attachSignin(element) {
    console.log(element.id);
    this.auth2.attachClickHandler(element, {},
        (googleUser) => {

         this._zone.run(() => {
          this.userAuthToken = googleUser.getAuthResponse().id_token;
          this.userDisplayName = googleUser.getBasicProfile().getName();
        });
        },(error) => {
          alert(JSON.stringify(error, undefined, 2));
        });
  }


  signOut() {
    this.auth2 = gapi.auth2.getAuthInstance();

    this.auth2.signOut().then(() => {
      console.log('User signed out.');
       this._zone.run(() => {
        this.userAuthToken = null;
        this.userDisplayName = "empty";
      });
    });

  }

 listFile() {
        var request = gapi.client['drive'].files.list({
            'pageSize': 10,
            'fields': "nextPageToken, files(id, name)"
          });

          request.execute(function(resp) {
            this.appendPre('Files:');
            var files = resp.files;
            if (files && files.length > 0) {
              for (var i = 0; i < files.length; i++) {
                var file = files[i];
                this.appendPre(file.name + ' (' + file.id + ')');
              }
            } else {
              this.appendPre('No files found.');
            }
          });
  }

  appendPre(message) {
    var pre = document.getElementById('output');
    var textContent = document.createTextNode(message + '\n');
    pre.appendChild(textContent);
  }
}

home.html

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="start()">Start</button>
  <button ion-button (click)="signOut()">Logout</button>
  <div class="main-application">
    <p>Hello, {{userDisplayName}}!</p>
  </div>
  <div id="gSignInWrapper">
    <div id="customBtn" class="customGPlusSignIn">
      <span class="icon"></span>
      <button ion-button class="buttonText">Google</button>
    </div>
  </div>

  <button ion-button (click)="listFile()">Get Drive</button>

</ion-content>

person Insane Rose    schedule 07.10.2016    source источник
comment
Я сделал npm install --save @types/google-drive-realtime-api, перешел по этому из вопрос. Однако я застрял после этого. Я вижу в вашем вопросе, что вы импортировали driveService. Можете ли вы сказать мне, что нужно сделать, чтобы использовать gapi. Спасибо :)   -  person Jilna    schedule 01.06.2017
comment
google-drive-realtime-api устарел ref. npm install --save @types/gapi.client.drive должен помочь вам продолжить ref   -  person Anand Rockzz    schedule 26.05.2019


Ответы (1)


Мой ответ: добавьте в index.html библиотеку Google API после тега <body>

 <script src="https://apis.google.com/js/platform.js" async defer></script>
person Insane Rose    schedule 09.10.2016