Persistent Angular Factory Variables Showing Outdated Data - Instances Stuck with Old Values

One of the challenges I faced was setting up a resource factory to build objects for accessing our API. The base part of the URL needed to be determined using an environment variable, which would include 'account/id' path segments when the admin user engaged with a client account.

However, there was an issue with the sessionStorage item holding the 'engagedAsId' not being read for instances created after engaging an account. A full reload of the app was required to reflect this change. Below is the relevant factory code:

myapp.factory('ResourceSvcFactory',
    ['$rootScope', '$resource', 
    function ($rootScope, $resource) {

    function ResourceSvcFactory (endpoint) {
        // vvv problem is here vvv
        var accountId = sessionStorage.getItem('engagedAsId');
        var apiPath = (accountId != null) 
            ? '/api/account/' + accountId + endpoint 
            : '/api' + endpoint;

        var Resource = $resource(apiPath+':id/',{
            // default params
            id:''
        },{
            // custom actions 
            update: {method: 'PUT'}
        });

        return Resource;
    }

    return ResourceSvcFactory;
}]);

myapp.factory('AssetsResource', ['ResourceSvcFactory', function (ResourceSvcFactory) {

    var endpoint = '/assets/';
    var Resource = ResourceSvcFactory(endpoint);

    return Resource;
}]);

The implementation in my Controller looks like this:

myapp.controller('AssetGroupListCtrl', [ 'AssetgroupsResource', function (AssetgroupsResource) {

    var AssetGroups = AssetgroupsResource;

    // ... rest of controller
}]);

Everything works fine when I run it. However, changing the engaged status in the sessionStorage without a full reload does not update the instance in the controller. Is there a way to automatically refresh the instance?

Answer №1

After conducting extensive research, I have realized that the main issue with my approach is trying to utilize a 'singleton' as a 'class.' As stated in the documentation:

Note: All services in Angular are singletons. This means that the injector only uses each recipe once to create the object and then caches the reference for future use. http://docs.angularjs.org/guide/providers

To work around this limitation, I decided to create the $resource within a method of a returned object. Here's an example of how I implemented it: MyApp.factory('AssetgroupsResource', ['$rootScope', '$resource', function ($rootScope, $resource) {

    return {
        init: function () {
            var accountId = sessionStorage.getItem('engagedAsId');
            var apiPath = (accountId != null) 
                ? '/api/account/' + accountId + endpoint 
                : '/api' + endpoint;
                // default params
                id:''
            },{
                // custom actions 
            });
            return Resource;
        }
    }
}]);

By structuring it this way, I was able to instantiate the object at the appropriate time within the controller:

MyApp.controller('AssetGroupListCtrl', ['Assetgroups', function (Assetgroups) {
    var Assetgroups = AssetgroupsResource.init();
    // now I can leverage angular's $resource interface
}]);

Hopefully, this solution proves helpful to others. (Or perhaps someone will enlighten me on a more concise three-line solution!)

Answer №2

When you need to trigger an update in Angular, simply use $scope.$apply();.

To learn more about this process, check out this helpful tutorial:

Answer №3

It appears that the $resource module is utilizing promises, which could potentially cause problems depending on how your factory is integrated into your controller.

Be cautious when using $scope.$apply() as it can lead to errors if not used correctly. A safer approach to ensure proper functioning of Angular is

$rootScope.$$phase || $rootScope.$apply();
.

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

Screen readers are unable to "read" text that is identified through aria-describedby

When enhancing my web application for accessibility, I encountered a challenge. I have implemented two required fields in a form that should display separate error messages as spans. To accomplish this, I am utilizing aria-invalid to signal when the fields ...

Setting up routeProvider in MVC4 with WebAPI2I will walk you through the process

I have a unique app that displays a dynamic calendar with various events. Upon clicking on an event, my goal is to effortlessly showcase detailed information below the calendar. The URLs for each event are created using a loop and look like this : &apos ...

sharing scope values between controllers in angularjs

utilizing getters and setters within services, subsequently invoking the service to retrieve values utilizing $Broadcast and $emit Which approach is considered best practice and what are the reasons behind it? ...

Exploring the Node.js view object within a function and delving into the reasons why a property of

As a beginner in programming, I am seeking tips on how to effectively learn node.js. Currently, I am utilizing the "Learning Behavior Driven Development with JavaScript" book for my learning journey. I would greatly appreciate any advice on how to view ob ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

When executed through nodeJS using the `require('./main.ts')` command, TypeScript Express encountered an issue with exporting and displayed undefined

Describing my issue is proving to be challenging, so I have simplified the code. Let me share the code below: main.ts import express from 'express'; let a = 1 console.log ('a in main.ts', a) export let b = a const app = express() let ...

Having trouble enabling push notifications on Android with ngCordova

Having trouble with push notifications through the ngCordova plugin. Followed the sample code from (with a slight change - no deviceready listener, code inside ionicPlatform.ready listener) Below is the code snippet: angular.module('myApp', [& ...

What is the process for transforming the outcome of a Javascript function into a webpage containing solely a JSON string?

I have a specific requirement where I need to fetch a URL and ensure that the only content displayed on the page is a JSON string. For instance, let's say I created a basic function called getDayOfWeek() to determine the current day of the week. The ...

"Enhancing the user experience: Triggering a window resize event in jQuery before page load on Magento

I am trying to trigger this function before the page finishes loading, but currently it only triggers after the page has loaded. Can anyone assist with this issue? $(window).on('load resize', function(){ var win = $(this); //this = window ...

Can a React component be configured to show only a specific array key when returning an array?

Just diving into the world of react and experimenting with different approaches to understand how I can transition into this new architecture. Currently, I have a basic component where I am returning an array of elements (mainly for testing purposes): cl ...

Tips on Modifying JSON Objects with JavaScript

In the code I'm working with, there's a generated line that creates an animated sidebar using a div. The width of this sidebar is controlled by the 'v' parameter, currently set to 85. <div id="sidebar" class="inner-element uib_w_5 ...

Click on a specific image in a table using Cypress with a specific source URL

I need help with a query for Cypress regarding a table of items, each item having active (blue) and not active (black) images. How can I set up this query? Below is an image of the table list: https://i.stack.imgur.com/74qzb.png And here is the HTML code ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

The function did not execute properly, resulting in the express route returning no value

Encountering some issues with Express routes that are behaving inconsistently despite having identical code execution. The goal is to have a client application make API calls like this: async search(){ const query = this.$refs.searchInput.value; ...

Angular UI date picker is currently experiencing an issue where the short date format is displaying incorrectly, showing past dates

The UI date picker is displaying the wrong date when a short date format is selected and a date from a previous year like 1921 is chosen. Instead of showing 1921, it displays as if it were in year 2021. This behavior is not correct and should show the sele ...

Customize dynamically loaded data via AJAX

I have a webpage that is loading a table from another source. The CSS is working fine, but I am facing an issue editing the table using jQuery when it's loaded dynamically through a script. It seems like my changes are not getting applied because they ...

What causes the non-reachable part of the ternary operator to be evaluated prior to updating the state with setTimeout?

Check out my latest code snippet for a react component that renders a massive component. While the huge component is still rendering, a loading indicator will be displayed. import * as React from "react"; import ReactDOM from "react-dom"; import {HUGECom ...

The program failed to run properly because it couldn't find the reference to Chart

I added chart.js to my project using npm with the command: npm install chart.js --save-dev. In the file "resources/assets/js/bootstrap.js", I included it by using: require('chart.js');. After running npm run dev in the console, it compiled succe ...

Why does the browser indicate that a GET request has been sent but the promise does not return anything?

Having trouble with a puzzling issue and unable to find any solutions online. I am attempting to make a basic HTTP get request to receive a JSON object from an API I created (using express+CORS). I have experimented with both Axios and VueResource, yet en ...

Refreshing a section of a webpage using AJAX and PHP

After creating a RESTful API in PHP, I can easily register information by accessing the address . This registration process involves sending a POST request. Below is an overview of my method: File: api.php <?php /* File: api.php */ private function ...