Angular 6 - Google Picker API 弹出窗口 [英] Angular 6 - Google Picker API Popup

查看:24
本文介绍了Angular 6 - Google Picker API 弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只能偶尔访问一次 Google Picker.每次打开应用程序时,Google Picker Popup 都不会打开.

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

app.component.html

按钮</a>

app.component.ts

 import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';@成分({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss']})导出类 AppComponent 实现 OnInit {@ViewChild('AllFilePick') AllFilePick: ElementRef;构造函数(私有元素引用:元素引用){}ngOnInit() {var s1 = document.createElement("script");s1.type = "文本/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=";this.elementRef.nativeElement.appendChild(s2);var s3 = document.createElement("脚本");s3.src = "https://apis.google.com/js/client.js?onload=SetPicker";this.elementRef.nativeElement.appendChild(s3);//console.log(this.AllFilePick.nativeElement);控制台.log(s1);控制台.log(s2);控制台.log(s3);}}

我什至尝试使用 ngAfterViewInit 构造函数来附加脚本标记.

assets/api-script.js

 函数 SetPicker() {var picker = new FilePicker({apiKey: ‘’,clientId: ‘’,buttonEl: document.getElementById("AllFilePick"),onClick:函数(文件){PopupCenter('https://drive.google.com/file/d/' + file.id + '/view', "", 1026, 500);}});}函数 PopupCenter(url, title, w, h){//.....}函数 FilePicker(用户){//配置//....}

以上完整版代码运行正常,但偶尔会打开弹出窗口.仅在多次刷新应用程序或第二天打开应用程序后才会触发弹出.Picker 在 Angular 中不能正常工作.

在 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) 文件中.

在组件(.ts 文件)中.

import { Component } from '@angular/core';声明 var gapi: 任何;声明 var 谷歌:任何;@成分({选择器:'应用选择器',templateUrl: './app-selector.component.html',styleUrls: ['./app-selector.component.css']})导出类 GoogleDriveSelectorComponent {developerKey = '此处的开发者/API 密钥';clientId = "client_id"范围 = ['轮廓','电子邮件','https://www.googleapis.com/auth/drive'//在此处插入范围].加入(' ');pickerApiLoaded = false;oauthToken?: 任何;加载GoogleDrive(){gapi.load('auth', { 'callback': this.onAuthApiLoad.bind(this) });gapi.load('picker', { 'callback': this.onPickerApiLoad.bind(this) });}onAuthApiLoad() {gapi.auth.authorize({'client_id': this.clientId,'范围':this.scope,'立即':假},this.handleAuthResult);}onPickerApiLoad() {this.pickerApiLoaded = true;}handleAuthResult(authResult) {让 src;如果 (authResult && !authResult.error) {如果(authResult.access_token){让视图 = 新 google.picker.View(google.picker.ViewId.DOCS);view.setMimeTypes("image/png,image/jpeg,image/jpg,video/mp4");让pickerBuilder = new google.picker.PickerBuilder();让picker = pickerBuilder.启用功能(google.picker.Feature.NAV_HIDDEN).setOAuthToken(authResult.access_token).添加视图(视图).添加视图(新的 google.picker.DocsUploadView()).设置回调(功能(e){如果(e[google.picker.Response.ACTION] == google.picker.Action.PICKED){让 doc = e[google.picker.Response.DOCUMENTS][0];src = doc[google.picker.Document.URL];console.log("选择的文档是", doc,"and URL is ",src)}}).建造();选择器.setVisible(真);}}}}

Able to access the Google Picker only once in a while. Google Picker Popup doesn't opens every time when I open the application.

I'm implementing Google Picker API in Angular 6. I kept separate file for the logic behind connecting the Google API in the assets folder of angular and by the help of document.createElement("script"), appended the javascript file. And I have an Anchor tag to getElementById in app.component.html.

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);

      }
    }

I even tried using ngAfterViewInit, constructor for appending the script tag.

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 
        //....
    }

The Above full version code runs properly but pop-up opens rarely, once in a while. Pop up triggers only after refreshing the application for several times or Opening the application next day. Picker doesn't works regularly in the Angular.

解决方案

In 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>

In component template (.html) file.

<button (click)="loadGoogleDrive()"><G-Drive</button>

In Component (.ts file).

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);
      }
    }
  }

}

这篇关于Angular 6 - Google Picker API 弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆