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.