问题描述
我一直在尝试在单独的登录组件中以角度2实现与Google的登录.我无法使用Google https://developers中提供的文档来实现它.google.com/identity/sign-in/web/signin
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回调函数时,Google登录确实可用.但我需要一个单独的组件,以便能够使用google按钮呈现登录并在其中接收回调,以进一步处理为用户收到的访问令牌
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实现SignIn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!