【发布时间】:2018-06-30 15:57:36
【问题描述】:
想要在不点击按钮的情况下执行this.auth2.attachClickHandler 中的代码。
想不通
要求
想要在页面呈现时无需点击任何按钮即可获得 google 授权。
当我点击 google 登录按钮时,代码正在运行并获取我的 google 身份验证令牌。
但是如何在不点击按钮的情况下执行它。
代码
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();
}
}
有人可以指导我吗?我还在学习。谢谢
【问题讨论】:
-
在 ngOnInit 上调用函数不起作用?
-
No Friend - 它在 ngOninit 上不起作用 - 函数正在等待按钮点击
-
即使您在导出类时实现 OnInit,例如 export class GoogleSigninComponent 实现 OnInit{ } ?
标签: javascript angular google-chrome oauth google-oauth