Возможность доступа к Google Picker только время от времени. Всплывающее окно Google Picker открывается не каждый раз, когда я открываю приложение.
Я реализую Google Picker API в Angular 6. Я сохранил отдельный файл для логики подключения Google API в папке ресурсов angular и с помощью document.createElement ("script") добавил файл javascript. И у меня есть тег Anchor для getElementById в 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.info(this.AllFilePick.nativeElement);
console.info(s1);
console.info(s2);
console.info(s3);
}
}
Я даже пробовал использовать ngAfterViewInit, конструктор для добавления тега скрипта.
активы / 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 [JS]](https://i.imgur.com/WsjO6zJb.png)


щелкните здесь Как реализовать вход через Google в Angular 2 с помощью Typescript и просто создайте index.html в папке вашего приложения, и вы на 100% решите эту проблему, так как та же проблема была у меня.
В 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).
<button (click) = "loadGoogleDrive()"><G-Drive</button>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.info("Document selected is", doc,"and URL is ",src)
}
}).
build();
picker.setVisible(true);
}
}
}
}В 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.info('Picked', data.docs);
}
});
}
Лучший способ авторизоваться во время входа в Google, а затем после того, как нам понадобится файл, просто выбирающий из диалогового окна выбора.
Если вы считаете, что это дублированный вопрос из вопроса, на который вы указали ссылку, используйте кнопку «ФЛАГ», чтобы пометить его как дубликат.