Assign the returned auth2 value to an Angular variable

I've been searching for a solution to my issue without much success, even though it seems like it should be an easy fix.

Currently, I am using AngularJS and Google auth2 for authentication to fetch the logged in user's information. My goal is to store the user's name in an AngularJS variable so that I can display it on the page temporarily.

Below is the relevant HTML code:

<meta name="google-signin-client_id" content="(client id here)">
<script src="bower_components/angular/angular.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<body ng-app="CalendarApp" >
  <div class="container" ng-controller="CalendarCtrl">
    <div class="header well" >
      <h1> Some heading </h1>
      <p id="welcometext"> Welcome, {{userName}} </p>
    </div>
  </div>
</body>

And here is the corresponding JavaScript:

var myApp = angular.module('CalendarApp', []);
myApp.controller('CalendarCtrl', ['$scope', function($scope) {
$scope.userName = "tst";

gapi.load('auth2', function() {
  auth2 = gapi.auth2.init({
    fetch_basic_profile: true,
    scope: 'profile'
  });

  // Sign the user in, and then retrieve their ID.
  auth2.signIn().then(function() {
    var profile = auth2.currentUser.get().getBasicProfile();
    $("#welcometext").text("Welcome, " + profile.getName()); 
    $scope.userName = profile.getName();
    console.log($scope.userName); 
  });
}); // gapi.load

Despite successfully fetching the user data, I'm encountering an issue where only "tst" is displayed instead of the actual name in

$scope.userName = profile.getName();
. Any assistance would be greatly appreciated. Thank you!

Answer №1

If you want to convert the promise from auth2.signIn() into a promise that works with the AngularJS digest cycle through the $q service, you can use $q.when:

gapi.load('auth2', function() {
  auth2 = gapi.auth2.init({
    fetch_basic_profile: true,
    scope: 'profile'
  });

  // Sign the user in, and then retrieve their ID.
  //auth2.signIn().then(function() {
  //USE $q.when to integrate with AngularJS digest cycle
  $q.when(auth2.signIn()).then(function() {
    var profile = auth2.currentUser.get().getBasicProfile();
    //$("#welcometext").text("Welcome, " + profile.getName()); //this is my current workaround, but don't like it.
    $scope.userName = profile.getName();
    console.log($scope.userName); //this prints the correct name
  });
}); // gapi.load

By converting the promise from gapi into a $q service promise, any changes to $scope will be recognized by the AngularJS framework through the .then method.

According to the documentation:

$q.when

Converts an object that may be a value or a (3rd party) then-able promise into a $q promise. This is handy when dealing with an object that could either be a promise or not, or if the promise originates from an untrustworthy source.

--AngularJS $q Service API Reference - $q.when

Answer №2

There is a simpler way to achieve this:

$scope.userName = profile.getName();

If eliminating jQuery doesn't solve the issue,

try the following approach:

$scope.userName = profile.getName();
$timeout(function() {
   $scope.$apply();
});

Regards, Bharat.

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

Aligning a div next to a text field in line

After numerous attempts, I am still struggling to align the 'add' button inline with my text field. The icon needs to be positioned correctly as shown below. I have experimented with grids and various other methods, but it refuses to cooperate. ...

Dynamic connections with Meteor and AngularJS

My publication relies on a specific parameter from the client, so when subscribing from the client side, I need to send this parameter to the server. I am utilizing the angular-meteor package and have come across the $subscribe wrapper. The syntax for usag ...

What is the best way to ensure that an element remains active even after a page refresh?

I have been using this code to activate the current element, which I came across on a website called "w3schools.com". However, whenever I refresh the page, the currently active element disappears. Is there a way to ensure that the active element remains hi ...

Tips for presenting validation messages from the server on the client side using react-query

Hey there! I have set up the Express route for the signup API call, which is functioning correctly on the server-side. However, my goal is to show these validation messages in real-time as the user inputs their credentials on the React client side app.post ...

Failed to transfer form data to server using ajax in Node.js

I am attempting to utilize AJAX to send form data to a Node.js server. I had previously inquired about this on the following post. Below is a glimpse of my code: <div id="inputid" style="width: 400px; height:400px"> <p> Kindly input value ...

The splice function in Angular is mistakenly removing a different record instead of the intended one that was

An issue with the Angular splice function is causing it to delete the wrong record. Here is the code snippet in question. Within the code below, when attempting to delete the record labeled "Pat," the code ends up deleting the record labeled "Max." Please ...

Nodejs: A function is expected in the instanceof check, but an undefined value was provided

Encountering a peculiar error while using node-webkit, here's a detailed example to replicate it: index.js: var jQuery = require('jquery'); var Backbone = require('backbone'); (function($){ var ListView = Backbone.View.extend( ...

Ways to transfer information between controllers in AngularJS

I am looking for guidance on how to transfer JSON data from FirstCtrl to secondCtrl using AngularJS. Any assistance or advice on how to achieve this would be greatly appreciated... Snippet from First.js: angular.module('myApp') .controller ...

My webpage effortlessly retrieved data without the need to manually click a button using JavaScript, and a subsequent button call was made

Could someone assist me with this issue? I am utilizing the fetch API and have it linked to a button. The problem I am facing is that even without clicking the button, my data is being fetched from the API. When I click the button to fetch data for the fir ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...

Whenever the user hits the "Enter" key, a new element will be generated and added to the bottom of an existing element

I am in need of creating a new element at the end of another element. For instance, let's say I have this element: <div id="elmtobetrig">Element that should be followed by another element when the user hits enter after this text. <! ...

Discovering the cause of Chrome freezing during the execution of an AngularJS application

I'm currently investigating a performance problem within an AngularJS application. During certain actions, the CPU utilization spikes to 100%, the Chrome browser becomes unresponsive, and I'm forced to manually end the process using Chrome' ...

Struggle with connecting to Firebase database

I've been grappling with errors while trying to build a list of users using Firebase's collection feature. https://i.sstatic.net/BTPMM.png I've provided the information I'm inputting below: https://i.sstatic.net/yVD0i.png This is my ...

Creating an HTML Canvas effect where images are placed onto another image

Looking to create a similar effect as seen on this website () On this site, users can upload their images (4000 * 400) and have the option to add Mickey Mouse ears over their image before saving it. The Mickey Mouse ear is resizable from all four sides f ...

Chunk loading in IE 11 has encountered an error

Having an issue with my website which is created using Angular 5. It seems to be malfunctioning in IE 11, and I am encountering the following error in the console: https://i.stack.imgur.com/Ek895.png Any insights on why my Angular code isn't functio ...

Guidance on Implementing Promises in Ionic 2 and Angular 2

Here are two functions that I need to implement: this.fetchQuizStorage(); this.retrieveQuizData(); fetchQuizStorage() { this.quizStorage.getAnswers().then(data => { return data; }); } retrieveQuizData() { this.quizData.getQuiz().t ...

Determine the position of a nested object within a multidimensional array using JavaScript/TypeScript

My objective is to obtain the complete index of a complex object within a multidimensional array. For example, consider the following array: var arr = [ { name: "zero", children: null }, { name: "one", children: [ { ...

Error message in Typescript: "Property cannot be assigned to because it is immutable, despite not being designated as read-only"

Here is the code snippet I am working with: type SetupProps = { defaults: string; } export class Setup extends React.Component<SetupProps, SetupState> { constructor(props: any) { super(props); this.props.defaults = "Whatever ...

Using the named default export syntax in Javascript ES6+

Does this syntax meet the requirements for exporting? export default debug = { myfunction: myFunction }; ...

The issue with the value of the textarea in Selenium automated tests using

I have a webpage with Javascript where I've implemented a textarea using the following code: var textarea = $("<textarea>"); textarea.change(() => { console.log(textarea.val()); }); When I update the value in the textarea and then chang ...