Sign-in with google user in an AngularJS app

2019-04-06 16:10发布

I read this tutorial in order to connect my AngularJS app with google sign-in. I added the google button as follows (just copy-pasting the tutorial):

In the head I added the meta tag:

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

And then added the button itself:

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

At first I just copied the onSignIn method (that's just a generic handler so I'm not copying it to the question) from the tutorial and put it in a <script>...</script> tag and it worked. I now want to put this method in an Angular controller. So I created a controller as follows:

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());
   }
}

And wrapped the button with a div:

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

My code doesn't get to the onSignIn method now and I'm trying to figure out what can I do.

2条回答
男人必须洒脱
2楼-- · 2019-04-06 16:30

If you follow the instructions, what you will end up with is window. onSignIn - try to run it in your browser JS console, now to have the same behaviour you will need to crate that function from your controller.

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;
}

Remember that code executed by 3rd party like onSignIn will need to call $scope.$digest, so angular is aware of model changes.

查看更多
时光不老,我们不散
3楼-- · 2019-04-06 16:34

Looking at your code, it seems like you might have to add listener for your function. To keep things simple, you can easily integrate google login in your app with this plugin. https://github.com/sahat/satellizer

查看更多
登录 后发表回答