Loading remote common data once in AngularJS and sharing it across multiple controllers: a guide

I have a challenge in my AngularJS application - I need to load a large dataset from an HTTP request just once and share it across multiple controllers. To achieve this, I created a factory that handles the data retrieval:

angular.module('app').factory('reportFactory', ['$http', function ($http) {
        var reportFactory = {};
        reportFactory.endPoint = 'ajax.php';
        reportFactory.getHugeData = function () {
            return $http.get(this.endPoint + '?query=CourseListQuery');
        };
        return reportFactory;
    }]);

Initially, I attempted the following approach:

angular.module('app').factory('CommonData', ['reportFactory', function CommonDataFactory(reportFactory) {
    var data = {};
    reportFactory.getHugeData().then(function (response) {
        data.courses = response.data;
    }, function (error) {
    });
    return data;

}]);

However, when trying to access log.warn(CommonData.courses); in my controller, the result returned was undefined.

I am looking for a way to effectively store the promise result and make it accessible throughout my AngularJS application.

How should I structure my code to ensure a single call is made to retrieve the data, and where should this call be executed?

Answer №1

Utilize a provider for data management.

angular.provider("UserData", [function() {
    this.userData = {};

    this.setUserData = function(userData) {
        this.userData = userData;
    };

    this.getUserData = function() {
        return this.userData;
    };
}]);

Subsequently, in the controller:

angular.controller("DataController", ['UserDataProvider', function(UserDataProvider) {
    var userData = UserDataProvider.getUserData();
}]);

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

Is it possible for me to declare attributes using a function object in a single statement?

Given an object obj, the following two-line statements can be defined: var obj ={} //this is an object obj.isShiny = function () { console.log(this); return "you bet1"; }; These two lines can be combined into a one-line statement ...

Transferring an image between two <td> cells within the same table

For a project, I'm working on creating a Checkers game. I have the checker board and pieces ready, but I'm struggling with the movement logic. My goal is to enable the image to move or transfer from one td element to another when clicked. A frie ...

Troubleshooting a CSS problem within mat-autocomplete component in Angular 7

While using mat-autocomplete, I noticed that when I select an option from the dropdown and then scroll through the main bar, the dropdown menu does not move along with the autocomplete input field. view image here Here is the code snippet: <td width ...

Error: Unable to access the currentTime property as it is not defined

Incorporating Videojs into my react application has presented a challenge. I am attempting to set the current time of the videojs player, but keep encountering an error that reads "cannot read property currentTime of undefined". Below is my approach: var ...

Utilizing Vue JS methods to control a div element

Currently enrolled in an online coding course that utilizes a bot to check code for accuracy. The task at hand is to modify the following code... <div id="app"> <form @submit.prevent="onSubmit"> <input v-model="userName"> < ...

Unable to observe modifications in json file within java project (jsp)

I am currently using IntelliJ IDEA to develop a web project with JSP. I retrieve data from a file called "customer.json", and when I click on a button, I update this file in the backend. However, after trying to fetch the updated data again, it still reads ...

Small-scale vue iterates through elements with v-for but fails to display them

I'm really interested in Petite-vue, but I've been struggling to get even the basic functionalities to work. Unfortunately, there isn't a lot of examples or tutorials available online for petite-vue. Can anyone suggest good resources? Right ...

Error retrieving api data following update to date format

After making some adjustments to the date format required by a railway API, I am facing an issue where no train data is fetched upon clicking the submit button. Below is the code snippet: searchTrain(e) { e.preventDefault(); let journeyDate = ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

The components declared in the index file are rendered on every route throughout the React application

I'm a beginner with React and I'm using react-router version 6.0.2. My issue is that I created a component for the router and then called this component in the index file. However, when I add another component to the index file, it gets rendered ...

The select2 plugin seems to be having trouble recognizing the Li click functionality

I have a select menu that is using the select2 plugin. I am trying to add a class to the <select> element when a menu option is clicked, but it doesn't seem to be working as expected even after testing with an alert. https://jsfiddle.net/ysm4qh ...

Trouble with Excel Office Script setInterval functionality

Trying to automatically recalculate an Excel worksheet every second using Office Script. Unfortunately, my initial approach did not succeed. function sendUpdate(sheet: ExcelScript.Worksheet) { console.log('hi'); sheet.calculate(true); } func ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Function that observes with the pipe syntax

Is it possible to apply map, switchMap, or any other operator in conjunction with a function that outputs an observable? The objective here is to transform the result of the observable function and utilize that value during the subscription to another ob ...

Vue.js: The href attribute in a link is different from the data

Having <a> href tag below, clicking will redirect to www.duckduckgo.com, with the value of page.publicWebsite being displayed as well. {{page.publicWebsite}} shows www.duckduckgo.com. Is everything functioning correctly? https://i.stack.imgur.com/ ...

Extract the text and value from an asp.net treeview by utilizing jQuery or JavaScript

On my website, I am using a TreeView controller. I have disabled node selection by setting SelectAction = TreeNodeSelectAction.None as I have the checkbox option enabled. However, this causes an error when trying to access the .href property of the node. T ...

Angular - Strategies for Handling Observables within a Component

I am new to Angular and recently started learning how to manage state centrally using ngRx. However, I am facing a challenge as I have never used an Observable before. In my code, I have a cart that holds an array of objects. My goal is to iterate over the ...

Exploring the integration of JSONP with the unmatched features of Google

I am attempting to utilize the Google maps directions API by using jquery $.ajax. After checking my developer tools, it seems that the XHR request has been completed. However, I believe there may be an issue with the way jquery Ajax handles JSON.parse. Y ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...

How to remove the horizontal scrollbar from material-ui's Drawer element

My drawer is displaying a horizontal scroll, despite my efforts to prevent it. I've tried adjusting the max-width and width settings in Menu and MenuItems, as well as using box-sizing: border-box. I also attempted setting overflow: hidden on the Drawe ...