如何使用 Typescript 在 Angular 2 中使用 Google 实现登录 [英] How to implement SignIn with Google in Angular 2 using Typescript
问题描述
我一直在尝试在单独的登录组件中以 angular 2 实现使用 Google 登录.我无法使用 Google https://developers 中提供的文档来实现它.google.com/identity/sign-in/web/sign-in
I have been trying to implement sign in with Google in angular 2 in a separate login component. I am unable to implement it with the documentation available in Google https://developers.google.com/identity/sign-in/web/sign-in
当我在我的 index.html 文件中声明我的脚本标签和谷歌回调函数时,谷歌登录确实有效.但是我需要一个单独的组件才能使用谷歌按钮呈现登录并在其中接收回调以进一步处理为用户收到的访问令牌
Google sign in does work when I declare my script tags and google callback function inside my index.html file. But I require a separate component to be able to render the sign in with google button and receive the callback in it to further process the access token which is received for a user
推荐答案
在你的应用程序 index.html
文件中添加这一行
Add this line in your app index.html
file
<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
这篇关于如何使用 Typescript 在 Angular 2 中使用 Google 实现登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!