我一直在尝试在单独的登录组件中以 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/