如何使用 Typescript 在 Angular 2 中实现 SignIn with Google

2024-03-09

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

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


在您的应用程序中添加此行index.html file

索引.html

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

组件.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 http://embed.plnkr.co/n0pFS3y74EpJzwgscrBu/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Typescript 在 Angular 2 中实现 SignIn with Google 的相关文章

随机推荐