【问题标题】:How to automate button click in angular 4 app?如何在 Angular 4 应用程序中自动单击按钮?
【发布时间】: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


【解决方案1】:

当您到达该页面时,您可以在 url 中保留一个查询参数,例如 ?google=true 并且在 ngAfterViewInit 中您可以检查是否设置了查询参数,如果是,那么您可以调用 google auth 否则不要

更多了解访问查询参数

https://www.tektutorialshub.com/angular-passing-optional-query-parameters-to-route/

【讨论】:

  • Deepak - 函数 - attachSignin - 正在执行 - 当我到达这个函数时执行停止 => this.auth2.attachClickHandler。此函数在其回调中使用 googleUser - 我如何在不调用此函数的情况下获取 googleUser
  • 放置 document.querySelector('#googleBtn').click();在点击处理程序之后,因此附加的点击函数被调用
猜你喜欢
  • 1970-01-01
  • 2019-01-31
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 2016-10-26
  • 2014-04-28
相关资源
最近更新 更多