javascript - 如何在 Angular 4 应用程序中自动单击按钮?

标签 javascript angular google-chrome oauth google-oauth

想要在不单击按钮的情况下执行 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/

相关文章:

javascript - firestore transaction.set(ref, data, {merge : true}) and transaction. update(ref, data) 之间有什么区别?

javascript - 当数字未知时,有没有办法遍历所有 jwplayer 实例?

angular - Angular 测试中访问 MatMenuTrigger 组件实例

angular - 如何在 ag-Grid Angular 设置中访问 c​​olumnDefs 中另一列的值?

angular 5 为 i18n 动态更改语言环境

google-chrome - Chrome开发者工具:缺少 “Resources”标签

html - 多个电子邮件输入由具有不同名称/ID/占位符的自动填充填充

javascript - JS中extends class旁边的<>有什么作用?

javascript - 未捕获的语法错误 : Unexpected token ILLEGAL in javascript

javascript - 我的日期差异功能在 chrome 中工作但在 firefox 中不起作用