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

问题描述 投票:32回答:6

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

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

angular typescript google-signin
6个回答
59
投票

在您的应用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上查看演示


16
投票

SRC / index.html的

在您的应用的index.html文件中,您需要在<head>部分添加:

<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>

分型/浏览器/环境/ GAPI /

你需要添加gapigapi.auth2到你的网站:

npm install --save @types/gapi.auth2
npm install --save @types/gapi

(请参阅此borysnquestion以更好地理解这一点)。

SRC /应用/ +登录/ login.component.ts

这是我的组件的文件,在这里你需要使用ngAfterViewInit()来使用gapi和获取auth。你可以按照这里的实施developers.google...sign-in/web/build-button

例如,这是我的模板:

<div id="my-signin2"></div>

并登录功能:

ngAfterViewInit() {
    gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'light',
        'onsuccess': param => this.onSignIn(param)
    });
}

public onSignIn(googleUser) {
    var user : User = new User();

    ((u, p) => {
        u.id            = p.getId();
        u.name          = p.getName();
        u.email         = p.getEmail();
        u.imageUrl      = p.getImageUrl();
        u.givenName     = p.getGivenName();
        u.familyName    = p.getFamilyName();
    })(user, googleUser.getBasicProfile());

    ((u, r) => {
        u.token         = r.id_token;
    })(user, googleUser.getAuthResponse());

    user.save();
    this.goHome();
};

更新:一段时间后,并考虑到评论,这个答案需要一个小的更新。


15
投票

使用箭头(=>)函数的词法范围使得let that = this;的使用变得不必要。

Pravesh的一个更清洁的例子,不需要使用that确定范围,将是:

的index.html

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

Component.ts

declare const gapi: any;

@Component({
  selector: 'google-signin',
  template: '<button id="googleBtn">Google Sign-In</button>'
})
export class GoogleSigninComponent implements AfterViewInit {

  private clientId:string = 'YOUR_CLIENT_ID.apps.googleusercontent.com';

  private scope = [
    'profile',
    'email',
    'https://www.googleapis.com/auth/plus.me',
    'https://www.googleapis.com/auth/contacts.readonly',
    'https://www.googleapis.com/auth/admin.directory.user.readonly'
  ].join(' ');

  public auth2: any;

  public googleInit() {        
    gapi.load('auth2', () => {
      this.auth2 = gapi.auth2.init({
        client_id: this.clientId,
        cookiepolicy: 'single_host_origin',
        scope: this.scope
      });
      this.attachSignin(this.element.nativeElement.firstChild);
    });
  }

  public attachSignin(element) {
    this.auth2.attachClickHandler(element, {},
      (googleUser) => {
        let profile = googleUser.getBasicProfile();
        console.log('Token || ' + googleUser.getAuthResponse().id_token);
        console.log('ID: ' + profile.getId());
        // ...
      }, function (error) {
        console.log(JSON.stringify(error, undefined, 2));
      });
  }

  constructor(private element: ElementRef) {
    console.log('ElementRef: ', this.element);
  }

  ngAfterViewInit() {
    this.googleInit();
  }
}

模板

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

Working Plnkr


7
投票

还有另一种与谷歌连接的方式:

在index.html中添加这些行:

<meta name="google-signin-client_id" content="YOUR-GOOGLE-APP-ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js"></script>

然后是一个示例代码,用于在组件(或服务,如果您需要)上写入:

import {Component} from "@angular/core";
declare const gapi : any;


@Component({ ... })
export class ComponentClass {
   constructor() {
      gapi.load('auth2', function () {
         gapi.auth2.init()
      });
   }

   googleLogin() {
      let googleAuth = gapi.auth2.getAuthInstance();
      googleAuth.then(() => {
         googleAuth.signIn({scope: 'profile email'}).then(googleUser => {
            console.log(googleUser.getBasicProfile());
         });
      });
   }
}

7
投票

截至目前,角度最新版本来了,大多数我们使用角度4/5/6,所以想给这个简单的解决方案登录社交所以真正想要它的人

Angular 4/5/6社交登录

在AppModule中,导入SocialLoginModule

import { SocialLoginModule, AuthServiceConfig } from "angularx-social-login";
import { GoogleLoginProvider, FacebookLoginProvider, LinkedInLoginProvider} from "angularx-social-login";


let config = new AuthServiceConfig([
  {
    id: GoogleLoginProvider.PROVIDER_ID,
    provider: new GoogleLoginProvider("Google-OAuth-Client-Id")
  },
  {
    id: FacebookLoginProvider.PROVIDER_ID,
    provider: new FacebookLoginProvider("Facebook-App-Id")
  },
  {
    id: LinkedInLoginProvider.PROVIDER_ID,
    provider: new FacebookLoginProvider("LinkedIn-client-Id", false, 'en_US')
  }
]);

export function provideConfig() {
  return config;
}

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    SocialLoginModule
  ],
  providers: [
    {
      provide: AuthServiceConfig,
      useFactory: provideConfig
    }
  ],
  bootstrap: [...]
})
export class AppModule { }

并在您的组件中使用它

通过导入以下模块

import { AuthService } from "angularx-social-login";
import { SocialUser } from "angularx-social-login";

如需完整参考,您可以查看他们的Github

它有demo非常简单的页面


2
投票

几乎没有一个对我有用,因为我想要Google制作的谷歌按钮。 @mathhew eon的代码工作但不使用他们的按钮。

所以我把google数据成功函数放在窗口上,它完美无缺!它还具有额外的优势,如果用户已经登录,它将自动调用googleLogin功能。

HTML

<div class="g-signin2" data-onsuccess="googleLogin" data-theme="dark"></div>

在你的index.html中把它放在头上:

<meta name="google-signin-client_id" content="YOUR-GOOGLE-APP-ID.apps.googleusercontent.com">
<meta name="google-signin-scope" content="profile email AND WHATEVER OTHER SCOPES YOU WANT">
<script src="https://apis.google.com/js/platform.js" async defer></script>

然后在你的ngOnInit

ngOnInit() {
    (window as any).googleLogin = this.googleLogin
}
public googleLogin(userInfo) {
    console.log(userInfo)
}

0
投票

除了我补充说,以前回答的一切都是一样的

声明var gapi:any;否则,你会得到错误。

SRC / index.html的

在应用的index.html文件中,您需要在以下部分添加:

<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>

分型/浏览器/环境/ GAPI /

你需要在你的打字中添加gapi&gapi.auth2:

npm install --save @types/gapi.auth2
npm install --save @types/gapi

(请参阅此borysn的问题,以便更好地理解这一点)。

SRC /应用/ +登录/ login.component.ts

这是我的组件的文件,在这里你需要使用ngAfterViewInit()来使用gapi和获取auth。您可以在此处执行developers.google ... sign-in / web / build-button

例如,这是我的模板:

<div id="my-signin2"></div>

并登录功能:

 declare var gapi: any;

ngAfterViewInit() {
   gapi.signin2.render('my-signin2', {
      'scope': 'profile email',
      'width': 240,
      'height': 50,
      'longtitle': true,
      'theme': 'light',
      'onsuccess': param => this.onSignIn(param)
  });
}

public onSignIn(googleUser) {
   var user : User = new User();

      ((u, p) => {
         u.id            = p.getId();
         u.name          = p.getName();
         u.email         = p.getEmail();
         u.imageUrl      = p.getImageUrl();
         u.givenName     = p.getGivenName();
         u.familyName    = p.getFamilyName();
      })(user, googleUser.getBasicProfile());

      ((u, r) => {
         u.token         = r.id_token;
      })(user, googleUser.getAuthResponse());

      user.save();
      this.goHome();
};
© www.soinside.com 2019 - 2024. All rights reserved.