如何将角度组件功能绑定到谷歌登录按钮

问题描述 投票:0回答:1

我是角度新手,所以请友善。我一直在努力弄清楚如何将谷歌登录回调按钮连接到我的角度组件。我正在尝试在客户端接收 OAuth 令牌,以便发送到我的后端,但我无法获取角度组件内的响应。我遇到的障碍是无法让谷歌按钮调用我的角度分量函数。

基于最新的 google 登录 api,为了通过 html 添加 google OAuth 按钮,您需要执行以下操作。我尝试通过他们的 javascript 库来做到这一点,但没有成功。

<html>
  <body>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    <script> 
    function handleCredentialResponse(e) {
      //e.credential contains the JWT token
    }
    </script>
    <div id="g_id_onload"
         data-client_id="YOUR_CLIENT_ID"
         data-callback="handleCredentialResponse">
    </div>
    <div class="g_id_signin" data-type="standard"></div>
  </body>
</html>

我想将其封装到一个组件中,并在我的 component.ts 文件中调用该函数。所以我用

onGoogleSignin
作为组件函数执行了以下操作。

<script src="https://accounts.google.com/gsi/client"></script>
<div    id="g_id_onload"
        [attr.data-client_id]="google_login_id"
        [attr.data-callback]="onGoogleSignIn">
</div>
<div    class="g_id_signin" 
        [attr.data-text]="buttonTxt" 
        [attr.data-theme]="theme"
></div>

该项目编译并运行,但是当我运行它时,我在控制台中遇到以下问题

[GSI_LOGGER]: The value of 'callback' is not a function. Configuration ignored.

属性绑定没有问题,但功能不起作用。所以我想出的唯一方法是将以下内容放入index.html文件中

  <script>
    function onGoogleSignIn(e) {
       console.log(e);
      window.authRef.zone.run(() => { window.authRef.googleSigninFunction(e); });
    }
  </script>

修改 component.html 以不绑定到组件函数,如下所示:

<div    id="g_id_onload"
        [attr.data-client_id]="google_login_id"
        data-callback="onGoogleSignIn">
</div>

然后将以下内容放入我的组件的构造函数中:

  constructor(
    private ngZone: NgZone)  {
    window['authRef'] = { component: this, zone: this.ngZone, 
      googleSigninFunction: (e:any) => this.onGoogleSignin(e), }; 
  }

所有这些都有效,但它需要依赖我的组件才能位于我的组件之外,这不是一个好的做法。我知道这只是因为我对角度缺乏一些基本的了解。

任何帮助将不胜感激

更新:

我确实在 OnInit 上添加了代码,以编程方式将代码注入到 DOM 中,以便当 google 需要绑定到它时它会存在。这使我不必手动将代码添加到index.html中,但我确信有一种更优雅的方法可以做到这一点。

javascript angular google-signin
1个回答
0
投票

您需要在组件的 .ts 文件中声明类似的内容

declare global {
  interface Window {
    onGoogleSignIn: (response: any) => void;
  }
}

然后在 ngOnInit 中像这样绑定函数,我还在 onInIt 函数中加载脚本,以便每次组件渲染时都会触发,将脚本保留在 index.html 文件中,有时不会渲染按钮

  ngOnInit(): void {
    const body = <HTMLDivElement>document.body;
    const script = document.createElement('script');
    script.src = 'https://accounts.google.com/gsi/client';
    script.async = true;
    script.defer = true;
    body.appendChild(script);
    window.onGoogleSignIn= this.onGoogleSignIn.bind(this);
  }

最后在函数中做你想做的事情

  onGoogleSignIn(res: any) {
    console.log(res);

  }
© www.soinside.com 2019 - 2024. All rights reserved.