想要在不单击按钮的情况下执行 this.auth2.attachClickHandler
内的代码。
无法弄清楚
要求
想要在页面呈现时获取 Google 授权,而无需单击任何按钮。
当我单击谷歌登录按钮时,代码正在运行并获取谷歌身份验证 token 。
但如何在不点击按钮的情况下执行它。
代码
import { Component, ElementRef, AfterViewInit } from '@angular/core';
declare const gapi: any;
@Component({
selector: 'google-signin',
template: '<button id="googleBtn">Google Sign-In</button>'
})
export class GoogleSigninComponent implements AfterViewInit {
private clientId: string = 'XXXXXX';
private scope = [
'profile',
'email',
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/contacts.readonly',
'https://www.googleapis.com/auth/admin.directory.user.readonly'
].join(' ');
public auth2: any;
ngOnInit() {
//this.googleInit();
}
public googleInit() {
let that = this;
gapi.load('auth2', function () {
that.auth2 = gapi.auth2.init({
client_id: that.clientId,
cookiepolicy: 'single_host_origin',
scope: that.scope
});
that.attachSignin(that.element.nativeElement.firstChild);
});
}
public attachSignin(element) {
let that = this;
console.log(this.auth2);
let x = document.querySelector('#googleBtn')//.click();
console.log(x);
//Execute code inside this attachClickHandler automatically
this.auth2.attachClickHandler(element, {},
function (googleUser) {
console.log(googleUser);
let profile = googleUser.getBasicProfile();
console.log('Token || ' + googleUser.getAuthResponse().id_token);
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
}, function (error) {
console.log(JSON.stringify(error, undefined, 2));
});
}
constructor(private element: ElementRef) {
//console.log('ElementRef: ', this.element);
}
ngAfterViewInit() {
this.googleInit();
}
}
有人可以指导我吗?我仍在学习。谢谢
最佳答案
当你到达该页面时,你可以在 url 中保留一个查询参数,例如 ?google=true ,在 ngAfterViewInit 中你可以检查是否设置了查询参数,如果设置了,那么你可以调用 google auth,否则就不要调用
了解有关访问查询参数的更多信息
https://www.tektutorialshub.com/angular-passing-optional-query-parameters-to-route/
关于javascript - 如何在 Angular 4 应用程序中自动单击按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48374480/