The AngularJS factory does not hold on to its value

I have developed a basic factory to store a value from my authService:

app.factory("subfactory",
        function() {
            var subValue = {};
            return {
                set: set,
                get: get
            };

            function get() {
                return subValue;
            }

            function set(value) {
                subValue = value;
            }
        });

I am storing the value like this in authservice - this code snippet demonstrates how I save the value using subfactory.set():

 mgr.getUser().then(function (user) {
        if (user) {
            var idToken = user.id_token;
            var dataIdToken = getDataFromToken(idToken);
            subfactory.set(dataIdToken.sub);
        } else {
            //console.log("User not logged in");
        }
    });

However, when I attempt to retrieve the object in the controller, it appears to be empty:

    vm.onGridLoad = function() {

        var storedValue = subfactory.get();

        console.log(storedValue);

Answer №1

I have a different approach to writing the factory than what is shown here.

app.factory("subfactory",
        function() {

           var service = {};
           service.subValue = {};

            service.save = save;

            return service;

            function save(value) {
                service.subValue = value;
            }
        });

After defining the factory, you can inject it into any controller where it's needed. There's no need for a get method as you can access the value using service.subValue directly. However, feel free to make adjustments according to your preference.

The code provided is not tested but should be sufficient to resolve the issue at hand.

If your Angular app is a single page application (spa), remember that if you reload the page after saving initial data, the JavaScript will also reload and the state saved in the factory will be lost. In such cases, consider storing important information in localStorage or similar mechanisms to retain data even after page reloads.

Answer №2

Remember to utilize the return statement when calling your service

function fetchData()
{
    return manager.getProfile().then(function (profile) {
        if (profile) {
            var accessToken = profile.access_token;
            var extractedData = extractDataFromToken(accessToken);
            dataStore.save(extractedData);
        } else {
            //console.log("User profile not found");
        }
    });
}

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

Retrieve libraries from package-lock.json file

I am tasked with extracting all the libraries and versions from the package-lock.json file. Let me provide some context. I am implementing a security module within Jenkins to create an inventory of libraries used in each application. The goal is to gather ...

I'm having trouble grasping the sequence of events in this async example

Currently, I'm delving into the world of JavaScript and Node.js, but I find myself facing challenges with asynchronous execution. I have a piece of code that may not be following best practices, but I am eager to understand why the file remains open w ...

Deploying a React App to Github Pages Results in a Blank Screen

After successfully uploading a simple react app onto GitHub pages using gh-pages, I attempted to import the Shards dashboard project (https://github.com/DesignRevision/shards-dashboard-react) onto my GitHub page. Unfortunately, all I see is a blank page. ...

Exploring Data within Data Structures

I am currently making two JSON requests in my code: d3.json("path/to/file1.json", function(error, json) { d3.json("path/to/file2.json", function(error, json2) { }); }); The structure of json 2 looks like this: [ { "city" : "LA", "locati ...

Is there a way to design a form that appears as though it's levitating above a div element?

I am new to web development and currently practicing by converting PSD designs into HTML pages. I am facing an issue where I need to create a form that appears to be floating on top of a div, with the form being taller than the div itself. Here is an illu ...

Guidelines for setting up a universal Handler using React and AXIOS

In my current project, I am utilizing ReactJs and AXIOS. My goal is to implement a global error handler without having to add a catch statement to each request throughout the codebase. To achieve this, I have created a service that consolidates all request ...

Why does Math.max.apply not prioritize the first parameter?

function findSmallestNumber(numbers){ return Math.min.apply(Math, numbers); } This code sets the context to be the Math object. However, this is not required because the min() and max() methods will still function properly regardless of the specified co ...

Canvas ctx.drawImage() function not functioning properly

I've encountered an issue while trying to display images in a canvas using my rendering function. Here is the code snippet: function populateSquareImages(){ for(var i = 0, ii = squares.length; i < ii; i++) { if(squares[i].hasImage) { ...

Assigning an interface to a useFetch object in Vuejs 3 and Nuxtjs 3: A step-by-step guide

Need assistance with assigning an interface to a useFetch object in Vuejs 3 Interface export interface ProdutoInterface { codigo: number nome: string } Componente const { data: produto, error } = await useFetch(config.API_BASE_URL+`/produto`) I&apos ...

What could be causing the discrepancy between the labels below the chart and the labels in the legend on the bar chart in Chart.js?

I'm looking to create a chart with labels on the xAxes and the same labels in the legend. I've tried various solutions, but so far, the best result I've achieved is shown in the code snippet below. However, all bars seem to be connected to m ...

What are the best practices for utilizing an array of routes?

I'm new to working with react but I noticed something strange. My routes are currently set up like this: <Main> <Route exact path="/home" component={Home} /> <Route exact path="/home1" com ...

Showing a group of users in real-time as they connect using Socket IO

I've been working on setting up a system in Socket IO to create a list of individuals who join a 'party room'. The plan is to lock the party room once all players are present, and then display views to users. However, I've hit a roadblo ...

JSON parsing error: an unexpected token was encountered

I have recently validated the JSON string response on this JSON formatter tool and it confirms that the JSON string is valid. Below is the function I utilized to serialize data into a JSON string: private string getJSONData() { obj_userSession = new ...

Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval. var Arrow = (function () { function Arrow() { this.intVariable = 1; this.itemId = -1; this.interval = 25; } Arrow.p ...

React Router Blank Page Conundrum

In a new project, I'm experiencing an issue where the content is not loading in despite using a similar React-Route setup that worked in a previous project. When I create a nav link in the root directory, it changes the path but the screen remains whi ...

Creating a registration and authentication system using firebase

When using Google authentication with Firebase, is the Signup and Login logic the same? I am creating a page for user authentication but I'm unsure if I should have separate pages for signing up and logging in. This confusion arises from the fact that ...

Is there a way for me to access the response from the PHP file I'm calling with Ajax?

I am just starting to explore ajax and jquery, and I recently found a code online that I'm tweaking for my own use. However, I am struggling with how to handle responses from PHP in this context. The current setup involves ajax POSTing to a php page ...

Tips for integrating the react-financial-charts library into your React and JavaScript project

While exploring the react-financial-charts library, I discovered that it is written in TypeScript (TS). Despite my lack of expertise in TypeScript, I am interested in using this library in my React+JS project due to its active contributions. However, I hav ...

Employing buffers and streams for data transmission

I am in need of a node.js program that can effectively handle a large JSON dataset with thousands of records. Specifically, I require a script that can extract only the "name" key from each record and transfer it to another file using streams. If there ar ...

button that smooth slides out using jquery

Here is the source code for a jQuery slideout: jQuery(function($) { $('#slideClick').toggle(function() { $(this).parent().animate({left:'0px'}, {queue:false, duration: 500}); }, function() { $(t ...