angular - 如何使用 Typescript 在 Angular 2 中使用 Google 登录

标签 angular typescript google-signin

我一直在尝试在单独的登录组件中以 Angular 2 实现 Google 登录。我无法使用 Google 中提供的文档来实现它 https://developers.google.com/identity/sign-in/web/sign-in

当我在我的 index.html 文件中声明我的脚本标签和谷歌回调函数时,谷歌登录确实有效。但是我需要一个单独的组件才能使用 google 按钮呈现登录并在其中接收回调以进一步处理为用户接收的访问 token

最佳答案

在您的应用 index.html 文件中添加这一行

INDEX.html

<script src="https://apis.google.com/js/platform.js" async defer></script>

Component.ts 文件

declare const gapi: any;
  public auth2: any;
  public googleInit() {
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email'
      });
      this.attachSignin(document.getElementById('googleBtn'));
    });
  }
  public attachSignin(element) {
    this.auth2.attachClickHandler(element, {},
      (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());
        //YOUR CODE HERE


      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
      });
  }

ngAfterViewInit(){
      this.googleInit();
}

模板html文件

<button id="googleBtn">Google</button>

Plunker 上查看演示

关于angular - 如何使用 Typescript 在 Angular 2 中使用 Google 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38846232/

相关文章:

angular - 隐藏 ngx 高级饼图图例

angular - RxJs 运算符、forkJoin 在 Angular 11 中显示超过 6 个参数的错误

javascript - 无法从单选按钮 ionic 3 获取值

javascript - typescript :找不到模块 'react-cards' 的声明文件

ios - 无法将 UIButton 的自定义类更改为 GIDSignInButton

angular - 获取 https ://site. azurewebsites.net/fa-solid-900.f0..d.woff2 404(未找到)

angular - Ionic 4 Angular Back Button 到上一页而不是 root?

javascript - Angular - 从 api 加载后在模板中显示数据

ios - OAuth2 请求额外的范围

android - Google 登录服务器实现返回 401