如何在angular 4应用程序中自动按钮点击?

时间:2018-01-22 03:59:43

标签: javascript angular google-chrome oauth google-oauth

想要在没有点击按钮的情况下在this.auth2.attachClickHandler内执行代码 无法弄清楚

要求
想要在页面呈现时进行谷歌授权,而无需点击任何按钮 当我点击谷歌登录按钮时,代码正在工作并取出google身份验证令牌 但是如何在不点击按钮的情况下执行它。

CODE

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();

  }

}

有人可以指导我吗?我还在学习。感谢

1 个答案:

答案 0 :(得分:1)

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

有关访问查询参数的更多信息

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