What is the best way to save the $http response in a variable that can be accessed from outside of the $http function in

Currently, I am in the process of learning Angular and JavaScript, and I have found Stack Overflow to be a great resource. However, this is the first time that I have been unable to find a solution to my issue within the existing questions and answers. Despite trying numerous solutions, nothing seems to be working for me.

To summarize: I am attempting to save the response from a $http get request (specifically user data) into a variable so that I can utilize it in other functions within this controller.

The following is my factory with the $http get function:

app.factory('getUserFactory', ['$http', function($http){ 
    return {
        getUserData : function(email, password) {
            return $http.get('https://xxxxxxx.xxx.xx/api/v1/user/', {
                headers: {
                    "Authorization": 'Basic '+ window.btoa(email +':'+password)
                }                
            });
        }            
    };
}]);

This is my controller along with its functions:

 app.controller('UserController', ['$scope','$http', 'getUserFactory', function($scope, $http, getUserFactory) {

 var user= {};    // Used to bind input fields from HTML file
 $scope.user = user;  

 $scope.userData = {}; // <-- HERE I WANT TO STORE RESPONSE

 $scope.logIn = function() {  // Function runs on click

        getUserFactory.getUserData(user.email, user.password).success(function(response){

        $scope.userData = response.objects[0];                                  
        });            
 };

Additionally, here is a simple onclick function I am using to test if everything is functioning correctly:

 $scope.consoleLog = function () {
        console.log($scope.userData);
    }; 

I suspect that my issue may be related to the asynchronous nature of JavaScript. I always trigger the $http get request first when the user clicks the 'log in' button, and then attempt to use the response to display user details. However, outside of $scope.logIn(), $scope.userData reverts back to being an empty object again.

Answer №1

It seems like you are attempting to execute the login method on click. Give this a shot:

$scope.logIn = function() {  // This function is triggered upon clicking

    getUserFactory.getUserData(user.email, user.password).then(function(response){

        $scope.userData = response.objects[0];  

    });            

};

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

What is the proper way to halt an iteration with the $q service in AngularJS

Trying to incorporate the $q service to introduce a pause in the iteration due to a condition that requires making API calls within a loop. Implemented the following method: function fetchData(id){ var deferred = $q.defer(); var data; Restangula ...

Possible problem that may arise when using Express without Jade

I've been experimenting with Express for my latest project, and I came across the suggestion to use the Jade template engine for views like this: /* GET home page. */ router.get('/', function(req, res, next) { res.render('index' ...

Using AngularJS to add a third-party module called ngIdle

Below is a controller that I am working with: (function () { "use strict"; var app = angular.module('Demo') .controller('MainController', ['$rootScope', '$scope', '$location', 'curUser',MainC ...

What is the best way to update an element with AJAX?

Within my <div> element, I have dynamically fetched content from a database and successfully performed database operations using AJAX. While I can load part of my page from another PHP file, I am looking to refresh the data in another <div> on ...

Incorporating a delete button onto an image using JavaScript

I am currently developing a BlogApp and facing difficulty in attempting to include a button on an image. The image is being retrieved from the Django database in JavaScript (HTML). My goal is to have a clickable button overlaid on the image. views.py def ...

What are some best practices for managing expired files in Single Page Applications (SPAs) without the need to refresh the browser

After completing a comprehensive Single Page Application (SPA) using AngularJS, everything seemed to be going smoothly. However, a common issue arises when all JavaScript files are initially loaded on first access, or some files are loaded in a lazy mode ...

Navigating URLs with Ajax Requests in CakePHP

How can ajax calls in javascript files located in the webroot be handled without PHP interpretation? In my project using CakePHP and require.js, I avoid placing javascript directly in views. To address this issue, I set a variable in the layout to store t ...

What is the best way to create a JSON string using JavaScript/jquery?

Is there a way to programmatically build a JSON string? The desired outcome should resemble the following: var myParamsJson = {first_name: "Bob", last_name: "Smith" }; Instead of constructing the entire object at once, I would prefer adding parameters one ...

Master the art of filtering rows in an HTML table based on a select option when the mouse is clicked

I am trying to create a table that displays only the rows selected in a dropdown menu. Here is an example: If "All" is selected, the table should display all rows. If "2017" is selected, the table should display only the rows that have "2017" in the sec ...

Accessing and handling hefty files in Node.js from a remote server

I am currently working on a project involving two servers that need to communicate with each other. Server1 sends requests to Server2 for parts of a file, which are then stored in one file on Server1. Server2 is responsible for receiving these requests and ...

Exploring the relationship between React component inheritance and asynchronous requests

I'm struggling to comprehend why this isn't functioning var link = window.location.href; var array = link.split('/'); var sub = array[array.length-1]; console.log(sub); var name; var posts; var upvotes; var ProfileFiller = React.creat ...

Having trouble retrieving the value from the input DOM element

Below is the html and JS code that I am working with: function controller() { document.write(document.getElementById("name").value) ; document.write(document.getElementById("id").value) ; } <input type="text" id= ...

Retrieve the value from the URL by parsing it using JSON

My goal is to extract the asciiName from a specific URL: http://services.gisgraphy.com/geoloc/search?lat=21.283300399780273&lng=72.9832992553711&radius=10000<br> I am utilizing ajax jsonp for this task. Below is the complete code snippet ...

Error encountered in Firefox: THREE.js throws a TypeError because 'global' is undefined

After attempting to integrate three.js into my code as a standalone script without using webpack, browserify or requirejs, I encountered an issue. My setup involves loading an external Angular app and extending it, but now I need my own version of THREE.js ...

Update the content within a document and implement jQuery to make it clickable

Within my webpage, there is a random occurrence of the word -FORM-. I am looking to replace this word with another text that includes dashes for creating a clickable div. Despite having some code that successfully replaces the text, it lacks the function ...

choosing a specific item using Cheerio that has a period in its class name

I am facing a challenge in extracting information from an HTML document using Cheerio. The HTML content cannot be modified as it originates externally. The specific element I need to extract has a class name containing a dot: <span class='prop-dat ...

The controller in AngularJS is not defined

I'm currently developing a small Angular project where I am utilizing the bootstrap calendar by mattlewis92. However, I am running into issues with my controller. Below is my .js file: 'use strict'; var app = angular.module('Calendri ...

WebStorm: React and Bootstrap autocomplete feature fails to function

After installing React and Bootstrap in WebStorm, I encountered an issue where the Bootstrap code highlighting was not working. Despite JSX functioning correctly, the problem with Bootstrap remains unresolved. Can anyone provide guidance on how to resolve ...

Methods for verifying the device on which a web application is currently operating

After developing a web application using node.js, express, angular, and bootstrap, I noticed that the layout and forms were not displaying correctly on all devices. Specifically, when running the app on a different device, such as an iPad or laptop, the fo ...

What is the method for locating the second Tuesday of every month, beginning on December 1st?

I have successfully implemented functionality to show/hide a button based on the time range, but I am now looking for a way to also include a check for every second Tuesday of the month starting from December 1st. Any suggestions on how I could modify my ...