Angular 1.5.0 - What is the reason for factory being invoked only once?

I am facing an issue with my html template where the data from an Angular factory is only loaded once when the page initially loads. Subsequent page openings show the same results from the first backend call, indicating a potential caching issue within the factory. Upon investigating with Chrome debug tools, I observed that Angular sends repeated GET requests with the same resource id on each page load.

The factory definition is as follows:

.factory('Company', ['$resource', '$routeParams', function ($resource, $routeParams) {
    return $resource('/companies/getCompany/:companyId', {}, {
        get: {
            method: 'GET',
            url: '/companies/getCompany/:companyId',
            params: {
                'companyId': $routeParams.companyId
            }
        },
        save: {
            method: 'POST',
            url: '/companies/updateCompany'
        },
        insert: {
            method: 'POST',
            url: '/companies/createNewCompany'
        }
    });
}])

This snippet shows the controller code:

.controller('MyController', ['$scope', '$location', 'Company',
    function ($scope, $location, Company) {
        Company.get(function (data) {
            $scope.company = data;
        });
    }]);

I am utilizing ng-click to navigate to the designated page:

<tr ng-repeat="company in companies"
    ng-click="redirectToCompanyForm(company.id)">


$scope.redirectToCompanyForm = function (companyId) {
   $location.url('/updateCompany/' + companyId);
}

A breakpoint set on the factory only causes the app to pause during the initial page access.

Why does my factory function execute only once and how can I address this recurring issue?

Answer №1

According to the information provided in the Angular docs:

It is important to note that all services in Angular are singletons. This means that the injector creates the object using each recipe only once and then stores the reference for future use.

Therefore, it is correct to say that all services are created once and cached by Angular.

Edit: A more suitable answer tailored to your specific situation can be found below:

$resource caching

If you wish to disable caching for a particular resource, you can do so by including options in the $resource call:

return $resource('/companies/getCompany/:companyId', {}, {
    get: {
        method: 'GET',
        params: {
            'companyId': $routeParams.companyId
        },
        cache: false // ADD THIS LINE
    }
}

Edit 2: As per the documentation, the first parameter of $resource is mandatory and must be a valid URL.

Answer №2

Consider utilizing lower level $http techniques within your controller.

While $resource is a great tool, in this scenario you may not need to save the data permanently.

Experiment with the $http.get method...

Alternatively, give the query() method a try.

$scope.myData = DataFactory.query();

Answer №3

The issue has been successfully resolved. The previous incorrect usage of the factory has been fixed. This section pertains to the factory module.

.factory('Company', ['$resource', function ($resource) {
    return $resource('/companies/getCompany/:id', null, {
        save: {
            method: 'POST',
            url: '/companies/updateCompany'
        },
        insert: {
            method: 'POST',
            url: '/companies/createNewCompany'
        }
    });
}])

Now, let's take a look at how the factory should be invoked:

Company.get({id: $routeParams.companyId}, function (data) {
    $scope.company = data;
});

As a result, the correct data is now displayed each time the page loads.

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

Protractor - Error: prop is undefined

Need assistance in identifying an error. Currently, I am learning Protractor and attempting to create a basic test using Page Object. //login_pageObject.js let loginContainer = function() { this.usernameInput = $("input.login-form-01"); this.passwordInp ...

The margin and width of a div element with the position set to fixed and display set to table-cell are not rendering correctly

Is there a way to keep my .nav-container position: fixed; without creating a gap between it and the .page-content at certain window widths? When I set the position to fixed, a small white line appears between the red background of the .nav-container and th ...

Issue with Rest API causing Phonegap Ionic app to be unresponsive on device

Currently, I am attempting to initiate a login call to an Express REST API using Passport Basic Strategy. Interestingly, everything seems to be functioning properly when accessing the API from a browser, but encounters issues when accessed from a device th ...

Steps for transforming a JSON into a Class to generate objects

My JSON data is displayed below: var nodeclienthash={ socket:null, init : function() { // Initializing socket.io this.socket = new io.Socket(this.config.host, {port: this.config.port, rememberTransport: false}); } }; I am currently looking t ...

What is the best way to ensure a DOM element exists before you can start manipulating it?

In my AngularJS application, I am utilizing Angular Material and md-select. When a user clicks on the md-select, a dropdown list appears and an overlay with the tag Name is added to the DOM. My goal is to add a class or style as soon as the user clicks on ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

How can refs be applied effectively in React applications?

I've been thinking about the role of refs in React and how they can address certain challenges for developers. However, I have found that the explanations provided in the React documentation are not very clear, and there seems to be a lack of helpful ...

Incorporate dynamic rules into a CSS stylesheet

I am trying to dynamically add a rule to my CSS for each element. Each rule should have a different background-image and name. However, I seem to be encountering an issue where the dynamically added div is not linking to the dynamically added CSS rule. I&a ...

Confirmation for deletion in HTML form

Is there a way I can include a confirmation message for deleting an item on my form button? Any suggestions on which JavaScript code to use? <script type="text/javascript"> function confirmDelete() { return confirm("Are you sure you want to delete ...

Having trouble accessing the property 'keys' of undefined in React event handling operations

I am currently working on implementing a button that executes Javascript code roshtimer(), along with the ability for users to trigger the command using hotkeys. Users should have the option to either click the button or press 'r' on their keyboa ...

What is the best way to activate a component within Angular 2 that triggers the display of another component through method invocation?

I have created a popup component that can be shown and hidden by calling specific methods that manipulate the back and front variables associated with the class. hide() { this.back = this.back.replace(/[ ]?shown/, ""); this.front = this.front.replace( ...

Establishing a secondary setTimeout function does not trigger the execution of JQUERY and AJAX

// Custom Cart Code for Database Quantity Update $('.input-text').on('keydown ' , function(){ var tr_parent = $(this).closest("tr"); setTimeout(function () { $(tr_parent).css('opacity', '0.3'); }, 4000); var i ...

What could be causing the repetition of the same cookie in my request header when using jQuery ajax?

Stuck in a dilemma for hours now, seeking assistance or suggestions from anyone who can help me out. To sum it up, I have an asp.net web api application where I am trying to fetch data from a web api and populate multiple dropdown lists on a page using jQ ...

A guide on efficiently incorporating a php variable into json format, then transferring it to ajax

My Sample Code var ajaxResponse = xmlhttp.responseText; //ajax response from my php file jsonData = JSON.parse(ajaxResponse); alert(jsonData.result); And in my PHP Script $resultValue = 'Hello'; echo '{ "result":"' . $result ...

Click on the checkbox to activate it using JavaScript

I'm trying to use JavaScript to toggle the checkbox status when clicking a button. The first button is supposed to uncheck the box and it's working correctly: function clear() { document.getElementById("check").checked = ""; } However, I al ...

Utilize JavaScript to compute and implement a deeper shade of background color

To dynamically apply darker shades of background using JavaScript, I have devised the following code. .event-list .bg{ background:#eee; padding:5px; } .grid .event-list:first-child .bg{ background: #2aac97 } .grid .event-list:nth-child(2) .bg{ backgrou ...

Is there a viable substitute for websockets that can be utilized on shared hosting platforms?

Are there any viable alternatives for websockets that can be used with shared hosting? While I'm aware of node.js, socket.io, and Express.js, I'm unable to use them in a shared hosting environment. If there are other options available for creatin ...

Interacting between C# and Node.js

I am looking to develop a GUI application using C# that will serve as a platform for Node.js. Specifically, I want to utilize Node's file system API to read files from a directory, and have my C# program generate a list (similar to a ListView) to show ...

What is a clever way to monitor the completion of a forEach loop using promises?

I'm new to promises and I'm attempting to use them for the first time. After the completion of the forEach loop, I want to call another function for additional processing. However, when using forEach, the function insertIDBEvents is only printed ...

The blend of Combination and Advanced Timeline triggers a "ReferenceError: Highcharts is not defined" error

Replication Steps First, download HIGHCHARTS 4.1.9 from http://www.highcharts.com/download Next, open the file index.html Then, click on Combinations > Advanced timeline An error message is displayed in Firebug and the chart does not appear: Referenc ...