Skip to content Skip to sidebar Skip to footer

Sign-in With Google User In An Angularjs App

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 t

Solution 1:

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() {
  functiononSignIn(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.

Solution 2:

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

Solution 3:

You didn't specify your version of AngularJS, but it shouldn't matter. I solved this for AngularJS 1.x as follows:

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 credentialsclient_id: $GOOGLE_API_CLIENT_ID
    }).then(functiononInit() { // 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
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script><scripttype="text/javascript"src="https://apis.google.com/js/platform.js"asyncdefer></script>

// In your login fragment
<divid="g-signin2"style="width: 200px; margin: 20px auto 20px auto;"></div>

Post a Comment for "Sign-in With Google User In An Angularjs App"