我在一个项目中使用了谷歌登录,用户可以从两种不同的模式登录。我已成功实施了Google登录网站https://developers.google.com/identity/sign-in/web/sign-in中提供的文档。问题是登录仅适用于首先初始化的一个模态。另一个不起作用。
答案 0 :(得分:1)
在app index.html文件中添加脚本
<script src="https://apis.google.com/js/platform.js" async defer></script>
应用组件
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: `
<create-account></create-account>
<signin></signin>`
})
export class AppComponent {
constructor() {}
}
创建帐户组件
import {Component} from '@angular/core';
@Component({
selector: 'create-account',
template: `<h1>{{title}} </h1>
<google-signin></google-signin>`
})
export class CreateAccountComponent {
title = "create account page";
constructor() {}
}
登录组件
import {Component} from '@angular/core';
@Component({
selector: 'signin',
template: `<h1>{{title}} </h1>
<google-signin></google-signin>`
})
export class SignInComponent {
title = "signin page";
constructor() {}
}
Google登录组件
import {Component, ElementRef, AfterViewInit} from '@angular/core';
declare const gapi: any;
@Component({
selector: 'google-signin',
template: '<button id="googleBtn">Google Sign-In</button>'
})
export class GoogleSigninComponent implements AfterViewInit {
private clientId:string = '409167539692-4eqnaq2jd1itl211gsgh3m2k7i02aefa.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() {
let that = this;
gapi.load('auth2', function () {
that.auth2 = gapi.auth2.init({
client_id: that.clientId,
cookiepolicy: 'single_host_origin',
scope: that.scope
});
that.attachSignin(that.element.nativeElement.firstChild);
});
}
public attachSignin(element) {
let that = this;
this.auth2.attachClickHandler(element, {},
function (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
}, function (error) {
console.log(JSON.stringify(error, undefined, 2));
});
}
constructor(private element: ElementRef) {
console.log('ElementRef: ', this.element);
}
ngAfterViewInit() {
this.googleInit();
}
}
上查看代码和测试演示