我看了this tutorial,以便将我的AngularJS应用与谷歌登录连接起来。我添加了google按钮,如下所示(只需复制粘贴教程):
在头部我添加了元标记:
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
然后添加按钮本身:
<div class="g-signin2" data-onsuccess="onSignIn"></div>
首先,我刚刚从教程中复制了onSignIn
方法(这只是一个通用处理程序,因此我没有将其复制到问题中)并将其放入{{1}标签,它工作。我现在想把这个方法放在一个Angular控制器中。所以我按如下方式创建了一个控制器:
<script>...</script>
用div包裹按钮:
app.controller('GoogleCtrl', function() {
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
}
}
我的代码现在没有使用<div ng-controller="GoogleCtrl">
<div class="g-signin2" data-onsuccess="onSignIn"></div>
</div>
方法,我试图弄清楚我能做些什么。
答案 0 :(得分:18)
如果您按照说明进行操作,最终会得到window. onSignIn
- 尝试在您的浏览器JS控制台中运行它,现在您需要从控制器中创建该功能所需的相同行为。< / p>
app.controller('GoogleCtrl', function() {
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
}
window.onSignIn = onSignIn;
}
请记住,由onSignIn
等第三方执行的代码需要调用$scope.$digest
,因此angular会知道模型更改。
答案 1 :(得分:3)
查看您的代码,似乎您可能需要为您的函数添加侦听器。为了简单起见,您可以轻松地将Android应用中的google登录与此插件集成。 https://github.com/sahat/satellizer
答案 2 :(得分:0)
您没有指定AngularJS的版本,但这没关系。我为AngularJS 1.x解决了以下问题:
allControllers.controller('authenticateController', ['$rootScope', $scope', function($rootScope, $scope) {
// do whatever you're doing on this page...
// initialize The GoogleAuth API explicitly
// The load an init below can be placed in your app.js in you feel like you want to implement the whole lifecycle Google provides.
gapi.load('auth2', function() { // Loads the auth2 component of gapi
gapi.auth2.init({ // initialize the auth2 using your credentials
client_id: $GOOGLE_API_CLIENT_ID
}).then(function onInit() { // on complete of init
gapi.signin2.render("g-signin2", { // render the HTML button on the screen providing the ID of the element (g-signin2)
onsuccess: function(googleUser) { // This executes when a user successfully authorizes you to their data by clicking the button and selecting their account.
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
// Do whatever you need to do to authenticate on your site.
}
});
});
});
}]);
// In your index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<script type="text/javascript" src="https://apis.google.com/js/platform.js" async defer></script>
// In your login fragment
<div id="g-signin2" style="width: 200px; margin: 20px auto 20px auto;"></div>