The output of an Angular factory function is consistently null

I am facing an issue with storing the currentUser object in a factory to make it accessible throughout my app. Despite ensuring that the user object is being received server side, whenever I call CurrentUserFactory.GetCurrentUser(), it returns null instead of the expected data.

angular.module('myWebApp.services')
    .factory('CurrentUserFactory', ['SettingsFactory', '$http', function(SettingsFactory, $http) {
            var CurrentUserFactory = {};
            var currentUser = null;

            CurrentUserFactory.GetCurrentUser = function() {
                if (!currentUser) {
                    $http.get(SettingsFactory.myAPIUrl + 'api/users/current', { withCredentials: true }).then(function (response) {
                        currentUser = response.data;
                    });
                }
                return currentUser;
            }

            return CurrentUserFactory;
        }
    ]);

Answer №1

When making an asynchronous call to $http, the function returns a promise, but the value of currentUser is initially null. In order to handle this scenario, you should return the $http promise if currentUser is null, or wrap currentUser in a promise and return that if it's not null:

angular.module('myWebApp.services')
    .factory('CurrentUserFactory', ['SettingsFactory', '$http', '$q', function(SettingsFactory, $http, $q) {
            var CurrentUserFactory = {};
            var currentUser = null;

            CurrentUserFactory.GetCurrentUser = function() {
                if (!currentUser) {
                    return $http.get(SettingsFactory.myAPIUrl + 'api/users/current', { withCredentials: true }).then(function (response) {
                        currentUser = response.data;
                        return response.data;
                    });
                }
                return $q.resolve(currentUser);
            }

            return CurrentUserFactory;
        }
    ]);

Usage:

Since the function returns a promise, you'll need to use a .then() block to access the results:

CurrentUserFactory.GetCurrentUser().then(function(currentUser) {
    console.log(currentUser);
});

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

Using Google Tag Manager to track the values of a formula field

I am looking to track the selected destination in a form using Google Tag Manager. To achieve this, I have created a custom JavaScript variable: function() { var inputField = document.getElementById("country"); return inputField.value || ""; } When ...

Deregister channel listener

My application has a functionality where users can subscribe to Twilio chat channels. When a user clicks on a channel, the chat opens up, messages are loaded, and the user is subscribed to receive new messages using this.state.channel.on('messageAdded ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...

Difficulties with angular ui-router authentication problems

When setting notify to true, the login.html does not render - it shows up as a blank page. However, if set to false, I receive multiple errors in the console: RangeError: Maximum call stack size exceeded at $.resolve (angular-ui-router.min.js:1) a ...

Error: Ajax unable to parse JSON - property 'name' does not exist in the object

When accessing my report.php file, it returns a json data. Here is the snippet of javascript code I am using to try and read the json: <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script> $(document).ready(function ...

What is the best way to transfer the value of one directive attribute to another directive in AngularJS?

For instance: <custom-main> <custom-sub1 att-name="test"></custom-sub1> <custom-sub2></custom-sub2> </custom-main> JavaScript Source Code bosAppModule.directive('custom-main',[&apos ...

What are the key distinctions between an arrow function, a class, and a traditional function?

Is there a way to distinguish between the following three elements in ES6 using its reference? let x = i => i+1; class y { constructor(i) { this._i=i+1; } get i(){ return this._i;} } function z(i) { return i+1; } For example: test(x) //=> ' ...

Navigating the process of returning a list from an AJAX method to a view through a controller in ASP.NET MVC

I need to retrieve a list from my controller and pass it to the view. Currently, I have the following script: function fetchNames(_id, _name) { $.ajax({ type: 'Post', url: 'GetNames/', data: { id: _id, name: _name}, su ...

Incorporate a fresh attribute to the JSON data in an Angular API response

I'm currently working on updating my JSON response by adding a new object property. Below is an example of my initial JSON response: { "products": [{ "id": 1, "name": "xyz" }] } My goal is to include a new object property ca ...

Locate records through an array of nested references using Moongoose (MongoDB)

Given the collection schema shown below: var terminalSchema = new mongoose.Schema({ name: 'String', ip: 'String' }); var wayPointSchema = new mongoose.Schema({ name: 'String', description: 'String' ...

Is it possible to use a custom filter along with data-ng-model? Problem arises when attempting to bind a custom filter with data-ng-model

I have created a custom filter to format input numbers into a specific format, like hh:mm. filter app.filter('formatDuration', function () { return function (duration) { if (angular.isUndefined(duration) || duration === null || dura ...

What is the best way to eliminate HTML <li> bullets using codebehind?

When working in codebehind, I often create an HTML list using the following method: HtmlGenericControl list = new HtmlGenericControl("ul"); for (int i = 0; i < 10; i++) { HtmlGenericControl listItem = new HtmlGenericControl("li"); Label textLabel ...

Why does the Formik form only validate after the second button click in this React Hooks, TypeScript, Formik, NextJS setup?

Looking for fresh perspectives on my code. The issue lies in the fact that it takes two submission attempts to validate the data inputted into a form successfully. It appears that the post request to Airtable happens before the validation schema, resulting ...

Unable to assign an ID to an element in JavaScript, as it will constantly be undefined

Is there a way to automatically generate unique IDs for jQuery objects if they don't already have one? I need these IDs for future requests. I wrote the following code, but it doesn't seem to be working. The ID's are not getting set and the ...

Guide to defining a conditional statement in a Nuxt.js application

I am working on displaying data from the Wordpress API in a Nuxt.js project. I am trying to organize the data by category, for example where ('post.category ', '=', 'categoryName '). Can anyone help me with the syntax in Vue.j ...

Creating Object of Objects in TypeScript: A Comprehensive Guide

Assuming I have a structure similar to this: interface Student { firstName: string; lastName: string; year: number; id: number; } If I intend to handle an array of these structures, I can simply specify the type as Student[]. Instead of utilizin ...

Dealing with event delegation on elements that are not nested

Working with Bootstrap group radio buttons where I need to implement event delegation. <div class="btn-group" role="group" aria-label="Basic radio toggle button group"> <input type="radio" class="btn- ...

Can someone explain the meaning of this code?

Recently, I came across a project where this line of code was used in a jQuery script. I'm not sure of its purpose and would appreciate some help understanding why it was included. If necessary, I can provide the entire function for reference. $("#ta ...

Tips on obtaining outcome by invoking a route outside of app.js

Within my file containing the request methods, the structure appears as follows: article.js router .route("/") .all((req, res) => { console.log("this should happen for any call to the article route"); }) .get((req, res) = ...

"Integrate a URL segment into the primary URL with the help of AngularJS or JavaScript

One interesting case involves a URL path that is structured in the following way. http://localhost:12534/urlpart1/urlpart2?querystring=140 The challenge here is to replace "urlpart2" with "urlpart3" using either javascript or AngularJS. One approach is t ...