Angular 2+中的Google登录按钮

时间:2016-10-05 17:25:46

标签: javascript angular google-api google-signin

我正在尝试通过其指南向Google添加登录/注销: https://developers.google.com/identity/sign-in/web/sign-in

但是我遇到了一些问题。

的index.html:

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://apis.google.com/js/platform.js" async defer></script>
  <meta name="google-signin-client_id" content="**my-google-api-key**.apps.googleusercontent.com">
  <script>
    gapi.load('auth2',function () {
      gapi.auth2.init();
    });
  </script>

app.component.html:

<div class="g-signin2" data-onsuccess="onSignIn"></div>
<a href="#" onclick="signOut();">Sign out</a>

app.component.ts:

public onSignIn(googleUser):void {
    var profile = googleUser.getBasicProfile();
    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
    console.log('Name: ' + profile.getName());
    console.log('Image URL: ' + profile.getImageUrl());
    console.log('Email: ' + profile.getEmail());
  }
  public signOut():void {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
    });
  }

问题:

  1. 在成功登录后,onSignIn函数不会被调用,因此没有打印任何内容但signIn正在运行。
  2. 在signOut函数中我有错误:“找不到名字'gapi'。”但是注销正在发挥作用。
  3. 问题:

    Google告诉我们不要使用googleUser.getBasicProfile()。getId()作为用户ID,而是使用ID Token intead:googleUser.getAuthResponse()。id_token.sub。 的为什么吗

3 个答案:

答案 0 :(得分:12)

我使用import { Component, NgZone } from '@angular/core'; ...... ...... constructor(ngZone: NgZone) { window['onSignIn'] = (user) => ngZone.run(() => this.onSignIn(user)); } ...... ...... onSignIn(googleUser) { //now it gets called ...... } 解决了这个问题。不确定它是否是最好的方式,但在我找到另一个之前它是最好的:)

$where = "";
if (!empty($full_name))
{
    $where .= "And full_name = '$full_name' ";
}
if(!empty($start_date))
{
    $where .= "And start_date >= to_date('$start_date','DD-MM-YYYY') ";
}

if(!empty($end_date))
{
    $where = "And end_date <= to_date('$end_date','DD-MM-YYYY') ";
}

答案 1 :(得分:1)

您只需将onSignIn方法添加到窗口即可通过以下代码进行调用。

constructor() {
    const _self = this;
    window['onSignIn'] = function (user) {
      _self.onSignIn(user);
    };
  }

onSignIn(googleUser) {
 // sign in code
}

这个链接可能会帮助您解决上一个问题。

Authenticate with a backend server

他们描述了:

  

警告:不要在后端服务器上接受普通用户ID,例如您可以使用GoogleUser.getId()方法获得的用户ID。修改过   客户端应用程序可以将任意用户ID发送到您的服务器   模仿用户,因此您必须使用可验证的ID令牌   安全地获取服务器端登录用户的用户ID。

答案 2 :(得分:1)

mrgoos的答案对我有所帮助,但是我们可以在没有NGZone的情况下使其变得更干净:

constructor() {
  window['onSignIn'] = this.onSignIn;
}