问题描述
我想在我的 Angular Universal 应用(使用 SSR)中实现 Google OneTap。我正在使用 Angular 11,并且在将应用程序转换为 Angular Universal 之前,以下脚本正在运行:
initGoogleOneTap() {
const domain = window.location.hostname;
google.accounts.id.initialize({
client_id: environment.GOOGLE_OAUTH_CLIENT_KEY,cancel_on_tap_outside: false,auto_select: true,state_cookie_domain: domain,callback: (response: any) => {
this.oneTapLogIn(response.credential)
.catch( (error) => {
console.error('Error logging in with Google One Tap: ',error);
});
},});
google.accounts.id.prompt( (notification: any) => {
if (notification.isNotdisplayed() || notification.isSkippedMoment()) {
// try next provider if OneTap is not displayed or skipped
}
});
}
我在脚本顶部使用 declare var google: any
。
我得到的错误是:ERROR ReferenceError: google is not defined
解决方法
首先,通过将其放入您的 index.html
<script src="https://accounts.google.com/gsi/client" async defer></script>
然后,像这样实现你的组件
declare var window: any;
ngOnInit() {
window.google.accounts.id.initialize({
client_id: 'YOUR CLIENT ID',callback: this.handleGgOneTap.bind(this)
});
window.google.accounts.id.prompt();
}
handleGgOneTap(resp) {
console.log('handleGgOneTap ',resp);
}