Log in using your Google credentials within an AngularJS application

I recently went through a tutorial on integrating Google sign-in with my AngularJS app. Following the tutorial instructions, I added the Google button in the following manner:

First, I included the meta tag in the head section:

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

Next, I inserted the button itself:

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

Initially, I directly copied the onSignIn method (a generic handler provided in the tutorial) into a script tag, and it worked. Now, I want to move this method into an Angular controller. So, I created a controller like this:

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

Then, I enclosed the button within a div:

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

Unfortunately, my code is not able to reach the onSignIn method now, and I am currently troubleshooting the issue to find a solution.

Answer №1

By following the steps provided, you will create the function window. onSignIn. To test it, run it in your browser's JS console. To replicate the same functionality, you must create 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;
}

Keep in mind that code executed by a third party like onSignIn will need to call $scope.$digest for Angular to recognize model changes.

Answer №2

Upon reviewing your code, it appears that you may need to implement a listener for your function. To streamline the process, you can seamlessly incorporate Google login into your application using this plugin. https://github.com/sahat/satellizer

Answer №3

Your version of AngularJS was not specified, but that shouldn't be a problem. I have successfully tackled this issue for AngularJS 1.x by following these steps:

allControllers.controller('authenticateController', ['$rootScope', $scope', function($rootScope, $scope) {
  // Carry out the necessary actions on this page...
  // Explicitly initialize The GoogleAuth API
  // The load and init code below can be placed in your app.js if you wish to implement the full lifecycle that 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());
          // Perform authentication actions on your site.
        }
      });
    });
  });
}]);
// Add to 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>

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update DataTable 1.9 while preserving existing rows

I'm currently using dataTables js version 1.9 Periodically, an ajax call is made to the server to retrieve information that should be displayed in a table every 60 seconds or so. Although I can easily clear and repopulate the table like this: $(id) ...

Instructions on creating a JSON patch in Django REST Framework

I have a PATCH button in my ModelViewSet https://i.sstatic.net/qoQLu.png class CompanyViewSet(viewsets.ModelViewSet): serializer_class = s.CompanySerializer queryset = m.Company.objects.all() def patch(self, request, id, format=None): ...

both modules loading at the same time in AngularJS

var moduleA=angular.module("MyModuleX",[]); moduleA.controller("MyControllerX",function($scope){ $scope.name = "John X"; }); var moduleB=angular.module("MyModuleY",[]); moduleB.controller("MyControllerY", function($scope) { $scope.name = "Sarah Y" ...

Troubleshooting problems with AngularJS currency formatting

Struggling with displaying numbers like 40.70 instead of 40.7? Need help! I've tried adding {{number:2}} in various places but can't seem to make it work. Any assistance would be greatly appreciated. This is the current HTML code I'm worki ...

Discover the "route" of a JSON element using JavaScript

I've been struggling to retrieve the "path" of a specific AngularJS scope variable. My end goal is to utilize this "path" as the ng-model for dynamically generated forms. Below is my current code: my_code.js: var my_data = { name: "fred", numbe ...

"Troubleshooting: ngForm.controls returning undefined value in Angular application

Trying to test this HTML code in Angular: <form name="formCercarUsiari" #formCercarUsuari="ngForm" class="tab-content"> <input #inputNif class="form-control input-height" maxlength="100" type="text" placeholder="Indiqui NIF" name="nif" i18n-pla ...

The issue arises when trying to escape double quotes within a regex pattern using ng-pattern

My ng-pattern validation includes a regex pattern ^[^\./:*\?\"<>\|]{1}[^\/:*\?\"<>\|]{0,254}$ to prevent invalid characters in file paths and set a limit. However, when I specify the ng-pattern as: ng-p ...

Dynamic JavaScript animation to retrieve the position of an element on-the-fly

I am currently exploring the world of animation in JavaScript and I have a few practical questions. In my script, I am attempting to "launch" a "rocket" upon clicking a "button". What I've observed is that although my function calculates values as int ...

When utilizing getServerSideProps, the data is provided without triggering a re-render

Although my approach may not align with SSR, my goal is to render all products when a user visits /products. This works perfectly using a simple products.map(...). I also have a category filter set up where clicking on a checkbox routes to /products?catego ...

Having trouble assigning more than one custom named property in TypeScript for MUI v5 Palette

I am currently setting up multiple custom attributes to make future updates easier. Nonetheless, I'm encountering a challenge with implementing more than one custom property in MUI v5. TypeScript Error TS2717: Subsequent property declarations must hav ...

Using jQuery to manipulate XML: Altering XML content using its ID with jQuery

Trying to modify content within an XML using jQuery has been a bit tricky for me. Based on the examples I've found, I believe the code should look something like this: Javascript: get_verrichtingen: function(){ var self = this; var option = ...

Implementing Firebase storage with AngularJS to bind images

Looking for assistance with displaying an image in an AngularJS view from a reference in Firebase Storage. I am able to retrieve the URL and print it in the console, but having trouble accessing it in the view. Service Code function getImageUrl(image) { ...

Creating an engaging Uikit modal in Joomla to captivate your audience

I need help optimizing my modal setup. Currently, I have a modal that displays articles using an iframe, but there is some lag when switching between articles. Here is the JavaScript function I am using: function switchTitleMod1(title,id) { document.g ...

`How can I effectively integrate react-i18next with the Semantic UI label element?`

Currently, I am working with Semantic UI along with the integration of [react-i18next][2]. My goal is to enable translation for label strings, but these labels include HTML tags, such as span. Unfortunately, the system only allows hardcoded or variable s ...

How to Link an Object's Value to a Checkbox in Vue

My goal is to populate the array selectedParks with the value of each item. However, I am facing an issue where the value is always set to the string "item" instead of the actual value of the Park Object. Here is the code snippet: <ul class="list- ...

Steps to restrict input in a text area to only backspace and cursor movements

I'm in search of a jQuery function that restricts movements to only arrow keys and backspace within a textarea. However, there seems to be an issue with the arrow key movements not functioning correctly. function moveArrow(e){ if(e.which >= 3 ...

I'm encountering difficulty accessing the Index value within the template's Ref

I'm having trouble accessing the index value inside the templateRef. It shows as undefined in the console. <ng-container *ngFor="let notification of notifications; let i = index"> <ng-template *ngTemplateOutlet="notificationPage ...

How can I force a Kendo UI Chart to resize in VueJS?

When integrating Kendo UI's Chart component within a Vue application, how can we trigger the chart to refresh or redraw? Although the chart automatically adjusts to changes in width by filling its parent container horizontally, noticeable stretching ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Using Local Storage with JavaScript and AngularJS

I have stored some data in local storage within the index.js file using JavaScript: var account = { name: name, email: email }; // Converts the object literal to a JSON string account = JSON.stringify(accoun ...