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 is the origin of the libraries found in npm-shrinkwrap that do not match the packages listed in package.json?

I'm puzzled by the presence of `express` in my `npm-shrinkwrap` file as a main dependency. Despite this, `express` is not listed as a dependency in my `package.json` file. I can't find any usage of it in my project. It's not included a ...

I am facing issues with installing React Router on my Windows device

After running the command to install react-router, this is the output from my prompt window: npm install --save react-router The prompt window shows several warnings and optional dependencies: npm WARN @babel/core requires a peer of @babel/core@^7.13 ...

Can you explain the functionality of the JavaScript code in the index.html file within webpack's react-scripts?

I have been experimenting with dynamically loading a React component into another application that is also a simple React app. However, I am facing challenges getting the index.js file to run properly. While referencing this article for guidance, I notice ...

Tips for shortening extra text in a non-wrapping HTML table cell and adding "..." at the end

My HTML template includes text imported from a database field into a <td> tag. The length of the text can range from 3 to 200 characters, and the <td> spans 100% of the screen width. If the text surpasses the width of the screen, I want it to b ...

Apply jQuery styling to new select box on page in order to maintain consistent styling throughout

I've encountered an issue with my jQuery select box styling. It appears to work perfectly on the initial page load, but when new content containing a select box is dynamically loaded onto the page, the styling doesn't get applied to it. Can anyo ...

Juggling PHP scripts within javascript

Can you help me with a question I have? I am working on multiple JS scripts, such as this one: <script> $('#mapveto1').click(function() { $('#mapveto1').addClass('banned'); $('#map1').text('cobble ...

Leverage environment variables within your index.html file

Currently, I am using Angular and I am encountering an issue while attempting to utilize an environment variable in my index.html for Google Analytics. I have attempted the following approach: <script> import {environment} from "./environments/e ...

The UseEffect Async Function fails to execute the await function when the page is refreshed

Having trouble calling the await function on page refresh? Can't seem to find a solution anywhere. Here's the useEffect Code - useEffect(() => { fetchWalletAddress() .then((data) => { setWalletAddress(data); setLoa ...

Using JavaScript onChange event with ModelChoiceField arguments

In my Django project, I have a Students model with various fields. I created a ModelChoiceField form allowing users to select a record from the Students table via a dropdown. forms.py: class StudentChoiceField(forms.Form): students = forms.ModelChoic ...

What is the best way to decrease the border width of a chartjs doughnut chart?

I have a vision for my chart based on the mockup: However, here is what I've been able to achieve using chartjs so far: This is the code I'm working with: datasets: [ { data: [3, 8, 13, 9, 2], backgroun ...

How to access the value of a $scope variable in HTML?

I am a beginner with Angular and I have encountered an issue. I am creating a variable in the Controller JS but I am unable to fetch it in the HTML part. <html ng-app='Demo'> <body> <h2>Select Your Symbol</h2> ...

Creating separate UI-views using ui-router within a single module

Can two independent ui-views be created using ui-router for a single module? The objective is to have the ui-views "know" where to display the current state, essentially creating a form of redirection. https://i.sstatic.net/OTNNL.png ...

What is the best way to simulate global variables that are declared in a separate file?

dataConfiguration.js var userData = { URIs: { APIURI: "C" }, EncryptedToken: "D" }; configSetup.js config.set({ basePath: '', files:['dataConfiguration.js' ], ..... UserComponentDetails: .....some i ...

What steps can I take to incorporate additional arguments into my function?

I am currently working with NodeJS, express, and passport. However, I believe this question is specifically related to JavaScript. Within my routes file, I have the following code: app.get( '/users', login_req, user.index); So, when a get requ ...

AngularJS textbox failing to recognize line breaks as expected

I am struggling with the following HTML code: <div class="form-group"> <div class="input-group col-sm-12"> <label for="" class="control-label">Comments</label> ...

Knockout.JS encounters difficulty retrieving the value attribute in a select tag when the data is sourced from the server

After making an ajax request and binding the dropdown list, I noticed that the select tag was not reading the value attribute. However, when I bind the drop down list in the view model, it does recognize the value. For example: It works if I bind the mode ...

Is it possible to use Node.js child processes without carriage returns?

My Node.js script is set up to handle some database operations by creating child processes using the spawn functionality. However, I encountered a strange issue where the output stopped displaying carriage returns. Here's an example of what was happen ...

Comparing ASP.NET Core and Node.js: A Closer Look at Their Similar

After working with Node.js for some time, I have gained a deep understanding of how it operates internally, including the event loop and other aspects. However, I can't help but notice that ASP.NET Core bears a striking resemblance to Node.js. ASP.NE ...

AngularJS Unleashed: The Art of Displaying Dynamic AJAX

Hey there, I have a concern about the best practice to show or hide an ajax loading animation while input/output operations are being performed. At present, I am managing the animation using this code: Javascript app.controller('MyController', ...

Issue with nodes/JavaScript: Array objects not being properly updated

Being new to Javascript and Node.js, I attempted to code a simple program that generates an array of planes with varying index values. I started by defining a plane object with default values and tried to update the index value in a for loop. However, whe ...