谷歌用angularjs登录

时间:2015-07-06 13:34:29

标签: javascript angularjs google-api

我需要在我的某个部分中使用“使用谷歌登录”按钮,因此我按照谷歌的文档整合了web sign-in。 我的问题是,我无法从视图中获取按钮,只能从索引(因为元标记在那里)。由于我使用状态,我不想放置代码。基本上,以下元标记必须与按钮同时呈现:

<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<meta name="google-signin-scope" content="profile email">

在我的模板中:

        <!--will not work since we're not in index file -->
        <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
        <script>
            function onSignIn(googleUser) {
                // Useful data for your client-side scripts:
                var profile = googleUser.getBasicProfile();
                console.log("ID: " + profile.getId()); // Don't send this directly to your server!
                // The ID token you need to pass to your backend:
                var id_token = googleUser.getAuthResponse().id_token;
                console.log("ID Token: " + id_token);
            };
        </script>

任何人都有这个问题并且知道一个有效的工作。 THX

1 个答案:

答案 0 :(得分:1)

您可以手动初始化auth2(g-signin2将自动使用它)。然后渲染按钮引用元素id。

完全正常的示例(只需替换YOUR_CLIENT_ID):

<html>
<body>
  <script>
    function onSignIn(googleUser) {
       alert('onSignIn!');
    }

    function onLoad() {
      gapi.load('auth2,signin2', function() {
        gapi.auth2.init({
          'client_id': 'YOUR_CLIENT_ID'
        });
        gapi.signin2.render('google_signin_button', {
            'onsuccess': 'onSignIn',
            'theme': 'dark'
        });
      });
    }
  </script>

  <div id="google_signin_button"></div>

  <script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
</body>
</html>