【问题标题】:Angular 6 - Google Picker API PopupAngular 6 - Google Picker API 弹出窗口
【发布时间】:2019-01-02 12:17:53
【问题描述】:

只能偶尔访问 Google 选择器。每次打开应用程序时,Google Picker Popup 都不会打开。

我正在 Angular 6 中实现 Google Picker API。 我在 angular 的 assets 文件夹中为连接 Google API 背后的逻辑保留了单独的文件,并在 document.createElement("script") 的帮助下附加了 javascript 文件。 我在 app.component.html 中有一个用于 getElementById 的 Anchor 标记。

app.component.html

<a routerLink="/" id="AllFilePick" #AllFilePick> Button </a>

app.component.ts

    import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';


    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })


    export class AppComponent implements OnInit {

      @ViewChild('AllFilePick') AllFilePick: ElementRef;

      constructor(private elementRef: ElementRef) { }


      ngOnInit() { 

        var s1 = document.createElement("script");
        s1.type = "text/javascript";
        s1.src = "../assets/api-script.js";
        this.elementRef.nativeElement.appendChild(s1);

        var s2 = document.createElement("script");
        s2.src = "https://www.google.com/jsapi?key=<API_KEY>";
        this.elementRef.nativeElement.appendChild(s2);

        var s3 = document.createElement("script");
        s3.src = "https://apis.google.com/js/client.js?onload=SetPicker";
        this.elementRef.nativeElement.appendChild(s3);

        // console.log(this.AllFilePick.nativeElement);
        console.log(s1);
        console.log(s2);
        console.log(s3);

      }
    }

我什至尝试使用 ngAfterViewInit,构造函数来附加脚本标签。

assets/api-script.js

    function SetPicker() {
        var picker = new FilePicker(
            {
                apiKey: ‘<API_KEY>’, 
                clientId: ‘<CLIENT_ID>’,
                buttonEl: document.getElementById("AllFilePick"),
                onClick: function (file) {             
                    PopupCenter('https://drive.google.com/file/d/' + file.id + '/view', "", 1026, 500);
                }
            }
        );
    }

    function PopupCenter(url, title, w, h)
    {
       //.....
    }

    function FilePicker(User)
    {
        //Configuration 
        //....
    }

以上完整版代码运行正常,但弹出窗口很少打开,偶尔会打开。 只有在多次刷新应用程序或第二天打开应用程序后才会弹出触发器。 Picker 在 Angular 中无法正常工作。

【问题讨论】:

    标签: javascript angular typescript google-api google-picker


    【解决方案1】:

    单击此处How to implement SignIn with Google in Angular 2 using Typescript 并在您的应用程序文件夹中创建 index.html,您将 100% 解决此问题,因为我也遇到了同样的问题。

    【讨论】:

    • 如果您认为这是您提供链接的问题的重复问题,请使用 FLAG 按钮将其标记为重复。
    【解决方案2】:

    在 index.html 中

     <script type="text/javascript" src="https://apis.google.com/js/api.js"></script>
      <script src="https://apis.google.com/js/platform.js"></script>
    

    在组件模板 (.html) 文件中。

    &lt;button (click)="loadGoogleDrive()"&gt;&lt;G-Drive&lt;/button&gt;
    在组件(.ts 文件)中。

    import { Component } from '@angular/core';
    declare var gapi: any;
    declare var google: any;
    
    @Component({
      selector: 'app-selector',
      templateUrl: './app-selector.component.html',
      styleUrls: ['./app-selector.component.css']
    })
    export class GoogleDriveSelectorComponent {
    
      developerKey = 'developer/API key here';
      clientId = "client_id"
      scope = [
        'profile',
        'email',
        'https://www.googleapis.com/auth/drive'//insert scope here
      ].join(' ');
      pickerApiLoaded = false;
      oauthToken?: any;
    
      loadGoogleDrive() {
        gapi.load('auth', { 'callback': this.onAuthApiLoad.bind(this) });
        gapi.load('picker', { 'callback': this.onPickerApiLoad.bind(this) });
      }
    
      onAuthApiLoad() {
        gapi.auth.authorize(
          {
            'client_id': this.clientId,
            'scope': this.scope,
            'immediate': false
          },
          this.handleAuthResult);
      }
    
      onPickerApiLoad() {
        this.pickerApiLoaded = true;
      }
    
      handleAuthResult(authResult) {
        let src;
        if (authResult && !authResult.error) {
          if (authResult.access_token) {
            let view = new google.picker.View(google.picker.ViewId.DOCS);
            view.setMimeTypes("image/png,image/jpeg,image/jpg,video/mp4");
            let pickerBuilder = new google.picker.PickerBuilder();
            let picker = pickerBuilder.
              enableFeature(google.picker.Feature.NAV_HIDDEN).
              setOAuthToken(authResult.access_token).
              addView(view).
              addView(new google.picker.DocsUploadView()).
              setCallback(function (e) {
                if (e[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
                  let doc = e[google.picker.Response.DOCUMENTS][0];
                  src = doc[google.picker.Document.URL];
                  console.log("Document selected is", doc,"and URL is ",src)
                }
              }).
              build();
            picker.setVisible(true);
          }
        }
      }
    
    }

    【讨论】:

      【解决方案3】:

      在 Index.html 中

      <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
      

      创建类似 googleDrivePickerService (.service.ts) 的服务

      import {Injectable} from '@angular/core';
      
      declare const gapi: any;
      declare const google: any;
      
      @Injectable({
        providedIn: 'root'
      })
      export class GoogleDrivePickerService {
      
        private clientId = 'YOUR_CLIEND_ID';
        private apiKey = 'YOUR_API_KEY';
        private appId = 'YOUR_APP_ID';
        private scope = 'https://www.googleapis.com/auth/drive.file',
      
        private oauthAccessToken = null;
        private pickerApiLoaded = false;
        private pickerCallback = null;
      
        public open(callback): void {
          this.pickerCallback = callback;
          gapi.load('auth', {'callback': this.onAuthApiLoad.bind(this)});
          gapi.load('picker', {'callback': this.onPickerApiLoad.bind(this)});
        }
      
        private onAuthApiLoad(): void {
          gapi.auth.authorize({
            'client_id': this.clientId,
            'scope': this.scope,
            'immediate': false,
          }, this.handleAuthResult.bind(this));
        }
      
        private onPickerApiLoad(): void {
          this.pickerApiLoaded = true;
          this.createPicker();
        }
      
        private handleAuthResult(authResult): void {
          if (authResult && !authResult.error) {
            this.oauthAccessToken = authResult.access_token;
            this.createPicker();
          }
        }
      
        private createPicker(): void {
          if (this.pickerApiLoaded && this.oauthAccessToken) {
            let view = new google.picker.View(google.picker.ViewId.DOCS);
            let picker = new google.picker.PickerBuilder()
              .enableFeature(google.picker.Feature.NAV_HIDDEN)
              .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
              .setAppId(this.appId)
              .setOAuthToken(this.oauthAccessToken)
              .addView(view)
              .addView(new google.picker.DocsUploadView())
              .setDeveloperKey(this.apiKey)
              .setCallback(this.pickerCallback)
              .build();
            picker.setVisible(true);
          }
        }
      }
      

      在您的组件 (.ts) 中,导入服务并添加到构造函数中,最后通过回调调用 open 函数。

      import {GoogleDrivePickerService} from '../services/googledrivepicker.service';
      
      constructor(
        private googleDrivePickerService: GoogleDrivePickerService
      ){}
      
      openGoogleDrivePicker(): void {
        this.googleDrivePickerService.open((data) => {
          if (data.action === 'picked') {
            console.log('Picked', data.docs);
          }
        });
      }
      

      【讨论】:

      • 在谷歌登录时授权的最佳方式,然后在我们需要文件时从选择器对话框中选择。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2016-04-09
      • 1970-01-01
      相关资源
      最近更新 更多