Angular 2+中的Google登录按钮

Sta*_*lfi 4 javascript google-api google-signin angular

我正在尝试通过其指南向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>
Run Code Online (Sandbox Code Playgroud)

app.component.html:

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

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.');
    });
  }
Run Code Online (Sandbox Code Playgroud)

问题:

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

题:

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

mrg*_*oos 12

我用它来解决它NgZone.不知道这是不是最好的方式,但它是最好的,直到我找到另一个:)

import { Component, NgZone } from '@angular/core';
......
......
constructor(ngZone: NgZone) {
  window['onSignIn'] = (user) => ngZone.run(() => this.onSignIn(user));
}
......
......
onSignIn(googleUser) {
  //now it gets called
......
}
Run Code Online (Sandbox Code Playgroud)