Angular 2+ 中的 Google 登录按钮 [英] Google sign-in button in Angular 2+

查看:22
本文介绍了Angular 2+ 中的 Google 登录按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过他们的指南向/从 google 添加登录/注销:https://developers.google.com/identity/sign-in/网页/登录

I'm trying to add a login/logout to/from google by their guide: https://developers.google.com/identity/sign-in/web/sign-in

但是我遇到了一些问题.

But I'm facing some problems.

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’."但注销工作正常.

问题:

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

Google tells us not to use the googleUser.getBasicProfile().getId() as the user ID but use the ID Token intead: googleUser.getAuthResponse().id_token.sub. Why?

推荐答案

我使用 NgZone 解决了这个问题.不确定这是否是最好的方法,但在我找到另一个方法之前它是最好的 :)

I solved it by using NgZone. Not sure if it's the best way but it's the best until I'll find another one :)

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

这篇关于Angular 2+ 中的 Google 登录按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆