The $http service factory in Angular is causing a duplication of calls

After creating an angular factory that utilizes the $http service, I encountered a problem where the HTTP request is being made twice when checking the network tab in the browser.

Factory:

app.factory('myService', function ($http, $q) {

var deferred = $q.defer();
var responseData = null;
var obj = {};

obj.getData = function(){
    $http.get('test.json').success(function(response){
        responseData = response;
        deferred.resolve(responseData);
    }).error(function(response){
        deferred.reject(responseData);
    });

    return deferred.promise;
}

obj.myData = function(){
    return responseData;
}

return obj;
});

Controller:

app.controller('myController', function($scope, myService){

myService.getData().then(function(){
   $scope.myDetails = myService.myData();
});

});

I am seeking advice on resolving the issue with my approach. Any suggestions would be greatly appreciated.

Answer №1

Your current approach to handling caching seems overly complex and may not be very effective. It's important to consider whether the data has already been loaded before making additional requests.

One solution could be implementing a Caching Service that simplifies the caching process and reduces the amount of code required.

angular.module("YourApp").factory("CachingService", [
    "$q",
    "$http",
    function ($q, $http,) {
        var cache = {};

        return {
            getFromCache: getFromCache
        };


        function getFromCache(url) {
            var deferred = $q.defer();

            if (cache[url]) {
                deferred.resolve(cache[url]);
            } else {
                return $http.get(url).then(function (result) {
                    cache[url] = result;
                    return result;
                });
            }
            return deferred.promise;
        }
     }
 ]);

Once you have set up the Caching Service, you can easily incorporate it into other services:

angular.module("YourApp").factory("myService", [
    "CachingService",
    function(CachingService){
        return {
             getData: getData
        };

        function getData(){
            return CachingService.getFromCache("test.json");
        }
    }
]);

Finally, in your controller, you can retrieve the cached data using the service:

app.controller('myController', function($scope, myService){

    myService.getData().then(function(result){
       $scope.myDetails = result.Data;
    });

});

Answer №2

Instead of returning $http, you should consider returning deferred.promise.

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

What seems to be the issue with Collapse.js in Bootstrap 3.3.4 on this page?

I am currently utilizing Bootstrap version 3.3.4. All of my resources are linked relatively and the HTML file is in the correct location for access. I am creating a 'Learn More' button that should display a collapsed unordered list either above ...

Overabundance of Recursive Calls in Node.js Project Dependencies

After a tiring day at work, I noticed an alert for Windows SkyDrive showing that files couldn't be uploaded due to the path being too long. The lengthy directory structure made me chuckle at the technological limitation. However, it got me thinking: ...

Whenever I try to utilize the "ng-list" in JavaScript, I encounter issues accessing the variable model

HTML <input type="text" ng-list ng-model="OtherHobby" />{{OtherHobby}} <br /> {{AllHobbys}} Javascript $scope.OtherHobby = []; $scope.AllHobbys = $scope.OtherHobby; I ran a test on this piece of code. The variable "OtherHobby" w ...

What is the method for assigning 'selective-input' to a form field in Angular?

I am using Angular and have a form input field that is meant to be filled with numbers only. Is there a way to prevent any characters other than numbers from being entered into the form? I want the form to behave as if only integer keys on the keyboard ar ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

In Vue, the concept of using the debounce method is not clearly defined

I am aware that using the arrow syntax for a method can cause 'this' to not be mapped to the Vue instance. In my case, I am utilizing lodash.debounce and I don't think I'm using the arrow syntax here? Encountering Error: Cannot read pr ...

What steps can be taken to issue an alert when the table does not contain any records?

Upon clicking the submit button, the value from the database is retrieved based on the hidden field ID and displayed in a table. If the value is present, it should load in the table; otherwise, an alert saying 'there is no record' should be displ ...

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

Sending Angular base64 image data to the server

I am encountering an issue while attempting to upload a base64 image from Angular to ExpressJS. The image is being created using html2canvas to generate the base64 representation. When I try to upload the imageData in its current format, I receive an error ...

Is it possible to modify the inactive color of just one radio button in Framework7?

Is there a way to change the inactive color of only one radio button in Framework7? I am aware that using the CSS variable --f7-radio-inactive-color allows me to set the inactive color for all radio buttons. However, I specifically want to modify the inac ...

Positioning the infowindow in Google Maps API v3

Creating a map with various markers, each with its own info window. However, when attempting to display an info window on multiple markers, the position remains fixed at the first clicked marker. What could be causing this issue? <script type="text/jav ...

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

The jQuery statements are not properly executing the if and else conditions

i'm currently assessing the condition using this particular code. jQuery(document).ready(function($){ $('#uitkering_funds').hide(); $('#uitkering_funds_hoofd').hide(); $('#partner_uitkering').hide(); $('#par ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

What is preventing this brief code from functioning properly? I am trying to extract a value from an input field and add it to a div element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="//ajax.googleapis.com/ajax/libs/jque ...

Is there a way to use Ajax to analyze and contrast information from two separate web links?

I am looking to compare and display the genre_ids from the first link and the id from the second link. Example: genre_ids: [ 18, 878, ] { id: 18, name: "Drama", }, { id: 878, name: "Science Fiction", } Result: Drama, Science Fiction $(document).ready( ...

Is it more effective to import an entire library or specific component when incorporating it into Create-React-App?

I have a question about optimizing performance. I understand that every library has its own export method, but for instance, on react-bootstrap's official documentation, it suggests: It is recommended to import individual components like: react-boo ...

How to remove a loop-rendered component from the DOM in Vue

My website has an image upload form where users can select multiple images. Once the images are selected, they are previewed and users can provide meta info such as Category and Type for each image. This functionality is implemented in the upload.vue file ...

Combining plugin setups and functionalities into a unified script

When it comes to grouping plugin initializations and scripts in a website, I often have a "tools.js" file that contains various functions, click events, and more. I prefer keeping all these script calls centralized in one file for simplicity, organization, ...

Calculating the Bounding Box of SVG Group Elements

Today I encountered a puzzling scenario involving bounding box calculations, and it seems that I have yet to fully understand the situation. To clarify, a bounding box is described as the smallest box in which an untransformed element can fit within. I h ...