Angular Universal 中的 Google OneTap

问题描述

我想在我的 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);
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...