Is there a way to ensure that my AngularJS factory fetches HTTP data only once?

I have implemented a factory in my project to share data among multiple controllers. Here is the code for my factory:

    var szGetData = "some url that works";
    myApp.factory('Data', function ($http) {
        var eventData = {};
        eventData.getEvent = function (event) {
                return $http.get(szGetData, event);
            }
        return eventData;
    });

Each of my controllers calls the factory in the same way, like this:

        Data.getEvent()
            .success(function (event) {
                $scope.eventData = event;

            })
            .error(function (error) {
                $scope.status = 'Unable to load customer data: ' + error.message;
            });

Although everything is functioning correctly and I am able to retrieve the data, the web-service is being called three times and each controller has its own copy of the data. I would prefer to have all controllers working with the same data and only make one call to the web-service. Any suggestions on how to achieve this would be greatly appreciated.

Answer №1

One way to manage the pending promise is by storing it and then returning it to all subsequent callers.

Alternatively, in case of a request failure, you can reset the promise so that the next call to getEvent (after a failure) will trigger another attempt.

var szGetData = "a valid URL here";
myApp.factory('Data', function ($http) {
    var eventData = {};
    var promise;
    eventData.getEvent = function (event) {
        if(!promise){
            promise = $http.get(szGetData, event)
                .error(function(){ // this step is not mandatory
                    promise = false;
                });
        }
        return promise;
    }
    return eventData;
});

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

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...

Is there a way for me to store the retrieved information from an API into a global variable using Node.js?

function request2API(option){ const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2 const request = new XMLHttpRequest(); request.open('GET', urlStart + ChList[option].videosList + keyPrefix + key); request. ...

You cannot use voice_channel.join() to create a music bot in discord.js v13

As I was working on a new music command feature for my Discord bot, I encountered an issue. Whenever I try to use the command -play {url}, I keep getting an error message that says: voice_channel.join is not a function. I searched through various resource ...

What could be the reason for my ng-init not functioning properly?

<body ng-init="user=${userID};month=${month};curPageNum=${currentPage}"> Using JSP, I set initial values in the body tag. However, in the controller, I have the following code: console.debug($scope.user + " "+$scope.month} The issue is that only ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

How would you define 'Idiomatic' in the context of Idiomatic Javascript?

During his initial discussion on TypeScript, Anders repeatedly mentions the term 'idiomatic javascript'. Can you clarify the specific definition of idiomatic in this context? I've attempted to research this on Wikipedia and Stack Overflow, ...

I possess a pair of UI tabs. Whenever a button located outside the tab is clicked, I am required to activate a distinct tab

As a beginner in Javascript, I recently encountered an issue with a UI tab element that contains two tabs. My goal is to create a button that, when clicked, will scroll up and activate the second tab. <style> .tab-container { overflow-x: ...

Issue encountered with create-next-app during server launch

Encountering an error when attempting to boot immediately after using create-next-app. Opted for typescript with eslint, but still facing issues. Attempted without typescript, updated create-next-app, and reinstalled dependencies - unfortunately, the prob ...

Utilizing NodeJS and Express to efficiently share sessions across various routes

I have a Node.js web application built with Express that has multiple routes. These routes need to be able to access and share the session data when interacting with users. The routes are separated into different js files from the main app file, app.js. I ...

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...

The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body '{"text": "hello"}'. Below is the s ...

Update the page's icon every 5 minutes

Looking for assistance in creating a script within Ionic that will either refresh a page every 5 minutes or call the API every 5 minutes. Attempted to utilize the $interval function with no success. Seeking guidance on how and where to begin this project ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

Is it possible to delete a <div> tag based on screen size using jQuery or JavaScript?

Hello, I was curious if it's possible to dynamically remove a specific div tag using jQuery or JavaScript when the screen reaches a certain size, for example 500px. ...

Incorporate a popup triggered by a specific class (highly probable)

I've been attempting to utilize Tampermonkey to incorporate a popup feature on pages within the Canvas Learning Management System (LMS). Specifically, I'm focusing on a forum where there is a "Reply" option following each post. This is where I wa ...

Dealing with lag problems while feeding a massive dataset into the Autocomplete component of Material-UI

In my React project, I have integrated the Autocomplete component from Material-UI to enhance user experience. However, when attempting to pass a large dataset of 10,000 items to the Autocomplete component as a prop, there is a noticeable delay of approxim ...

Customizing Attribute for Material UI TextField

I'm currently in the process of adding a custom data attribute to a TextField component like so: class TestTextField extends React.Component { componentDidMount() {console.log(this._input)} render() { return ( <TextField label= ...

How to Assign a Specific ID to the Body Tag in Wordpress Using functions.php

Struggling to find a simple solution after scouring the web for answers. Most tutorials are overly complicated. I'm attempting to integrate a jQuery menu system into my Wordpress site and want to assign a unique body ID to make targeting easier. I p ...

Exploring the Wonder of MVC with Ajax Calls Handling Multiple Parameters

I've been struggling to send 2 parameters from the View to the controller using an ajax call. Everything was working fine when I had only one parameter, but as soon as I added another, the function stopped working. Below is the Javascript code with a ...