AngularJS 中的 Google 登录按钮有时不显示

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

我点击此链接 https://developers.google.com/identity/sign-in/web/sign-in 在基于 Angular 的网站上获取 Google Signin。

我看到了一些奇怪的行为。登录按钮有时会显示,但并非总是显示。当我刷新页面时,只有五分之一的刷新会出现该按钮。

我在 Chrome 和 Safari 中尝试过,两者都有相同的行为。

代码:

index.html

<script src="https://apis.google.com/js/platform.js" async defer></script>

<meta name="google-signin-client_id" content="my_client_id">

登录.html

<div class="g-signin2" data-onsuccess="onSignIn"></div>  

登录.js

angular.module('app').controller('LoginCtrl', function($scope) {
    window.onSignIn = function(googleUser) {
        // Get some info
    }
});
angularjs google-signin
3个回答
32
投票

我的猜测是,platform.js 脚本等待 DOM-ready 事件,然后使用“g-signin2”类查找您的 div。不过,在 Angularjs 中,事情有点不同。它有时起作用的原因是,有时你的 div 已由 Angular 渲染,有时在 Dom-ready 事件之前尚未渲染。 有 documentation 介绍如何使用您自己的 javascript 获得相同的结果。 我做了一个遵循您的路由的示例。

<!doctype html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div ng-view></div>

<script src="https://apis.google.com/js/platform.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.6/angular-route.min.js"></script>
<script>
    angular.module('app',['ngRoute'])
            .config(['$routeProvider',function($routeProvider){
                $routeProvider
                        .when('/log-in', {
                            template: '<button ng-click="logInCtrl.onLogInButtonClick()">Log In</button>',
                            controller: 'LogInController',
                            controllerAs: 'logInCtrl'
                        }).otherwise({
                            redirectTo:'/log-in'
                        });
            }])
            .controller('LogInController',function(){
                var self = this; //to be able to reference to it in a callback, you could use $scope instead
                gapi.load('auth2', function() {//load in the auth2 api's, without it gapi.auth2 will be undefined
                    gapi.auth2.init(
                            {
                                client_id: 'CLIENT_ID.apps.googleusercontent.com'
                            }
                    );
                    var GoogleAuth  = gapi.auth2.getAuthInstance();//get's a GoogleAuth instance with your client-id, needs to be called after gapi.auth2.init
                    self.onLogInButtonClick=function(){//add a function to the controller so ng-click can bind to it
                        GoogleAuth.signIn().then(function(response){//request to sign in
                            console.log(response);
                        });
                    };
                });
            });
</script>
</body>
</html>

或作为指令:

<!doctype html>
<html lang="en" ng-app="app" ng-controller="MainController">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <google-sign-in-button on-sign-in="onSignIn(response)" g-client-id="CLIENTID.apps.googleusercontent.com"></google-sign-in-button>

<script src="https://apis.google.com/js/platform.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script>
    angular.module('app',[])
            .controller('MainController',['$scope', function ($scope) {
                $scope.onSignIn=function(response){
                    console.log(response);
                }
            }])
            .directive('googleSignInButton',function(){
                return {
                    scope:{
                        gClientId:'@',
                        callback: '&onSignIn'
                    },
                    template: '<button ng-click="onSignInButtonClick()">Sign in</button>',
                    controller: ['$scope','$attrs',function($scope, $attrs){
                        gapi.load('auth2', function() {//load in the auth2 api's, without it gapi.auth2 will be undefined
                            gapi.auth2.init(
                                    {
                                        client_id: $attrs.gClientId
                                    }
                            );
                            var GoogleAuth  = gapi.auth2.getAuthInstance();//get's a GoogleAuth instance with your client-id, needs to be called after gapi.auth2.init
                            $scope.onSignInButtonClick=function(){//add a function to the controller so ng-click can bind to it
                                GoogleAuth.signIn().then(function(response){//request to sign in
                                    $scope.callback({response:response});
                                });
                            };
                        });
                    }]
                };
            });
</script>
</body>
</html>

写完前面的例子后,我发现了一种更好、更简单的方法来实现它。使用此代码,您可以像平常一样继承相同的按钮。

<!doctype html>
<html lang="en" ng-app="app" ng-controller="MainController">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <meta name="google-signin-client_id" content="CLIENTID.apps.googleusercontent.com">
</head>

<body>
  <google-sign-in-button button-id="uniqueid" options="options"></google-sign-in-button>

  <script src="https://apis.google.com/js/platform.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
  <script>
    angular.module('app', [])
      .controller('MainController', ['$scope',
        function($scope) {
          //for more options visit https://developers.google.com/identity/sign-in/web/reference#gapisignin2renderwzxhzdk114idwzxhzdk115_wzxhzdk116optionswzxhzdk117
          $scope.options = {
            'onsuccess': function(response) {
              console.log(response);
            }
          }
        }
      ])
      .directive('googleSignInButton', function() {
        return {
          scope: {
            buttonId: '@',
            options: '&'
          },
          template: '<div></div>',
          link: function(scope, element, attrs) {
            var div = element.find('div')[0];
            div.id = attrs.buttonId;
            gapi.signin2.render(div.id, scope.options()); //render a google button, first argument is an id, second options
          }
        };
      });
  </script>
</body>

</html>


0
投票

我找到了另一种方法来稍微简单地解决问题。

@sniel 的解释很完美,但我会让你知道更简单的解决方案。

您可以使用下面的示例代码,与使用 $watch 非常相似 https://developers.google.com/identity/sign-in/web/build-button

<!-- html part -->
<div id="signInButton"></div>


//gapi is Asynchronously loaded so you need to watch
$scope.$watch('gapi', function(newValue,oldVale){
        if(newValue !== oldVale){
            if(gapi){
                gapi.signin2.render('signInButton',
                    {
                        'onsuccess': $scope.onSuccess,
                        'onfailure': $scope.onFailure,
                        'scope':'https://www.googleapis.com/auth/plus.login'
                    }
                );
            }
        }
    });

0
投票

我遇到的问题是订单。 google 脚本在 DOM 元素准备好之前加载并执行。如果我在文档准备好后强制加载谷歌脚本文件,它就解决了我的问题。

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