Exploring AngularJS for real-time updates from a persistent database

Hello, I'm new to Angular and currently working on an app that requires frequent polling of a URL every second. The retrieved data needs to be stored persistently for access across multiple views and controllers.

To handle this, I've placed the HTTP request in a factory where the data is accessed by controllers through factory functions. However, I'm facing an issue where the factory function is executed before the HTTP request, causing errors in my app.

Below is the code snippet:

App.factory('metrics', function($http){
    var service;
    var users = [{laps:[]}];
    var updateMetrics = function(){
        // Function to update the users array in the factory
    };
    $http.get('data.csv').success(function(data) {
        var temp_array = data.split(" ");
        updateMetrics(0, temp_array);
    });

    service.lastLapInfo = function(){
        var lastlap = [];
        for (var i=0; i<users.length;i++)
        {
            var lap = users[i].laps[users[i].laps.length-1];
            lastlap.push(lap);
        }
        return lastlap;
    };
    return service;
});

App.controller('mainController', function($scope, $http, metrics) {
    $scope.users=metrics.lastLapInfo();
});

The call to "lastLapInfo()" is happening before the HTTP request, which results in errors due to empty data array. Any suggestions on how to resolve this?

Also, if there's a better approach to achieve the desired functionality instead of using a Factory, please advise!

Answer №1

Here is an example of how to use a promise, like Angular's $q service.

This method involves creating a factory that returns a promise:

App.factory('metrics', function($http){
   var service;
   ...
   service.load = function () {
      return $http.get('data.csv');
   });
   return service;
});       

In the controller, you would then call your metrics service and utilize the promise it returns:

App.controller('mainController', function($scope, $http, metrics) {
    metrics.load().then(function(response) {
       // This section confirms that the request has completed
       // You can either call the service again for more information or handle additional logic here.
    });
});

Answer №2

If you are unable to access the data right away, you can handle this by either indicating it in the return value (null, undefined, []), or you could opt to return a promise instead. This promise can be stored and resolved later once the data is retrieved.

For example:

var deferred = null;

$http.get(...).then ({
  if (deferred) {
    deferred.resolve(result);
    deferred = null;
  }
});

service.dataInfo = function(){
  if (no info available) {
    deferred = $q.defer()
    return deferred;
  }
  else {
    return data;
  }
};

This approach should work, depending on your desired structure.

Edit: included link to $q from comment.

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

Strategies for Implementing Multi-Step Password Form Validation

Currently, I am using https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps as the foundation of my form with some adjustments. Validation is functioning correctly where empty fields disable the next button. However, when I attempt to add ...

Using Node.js, we can create a program that makes repetitive calls to the same API in a

My task involves making recursive API calls using request promise. After receiving the results from the API, I need to write them into an excel file. Below is a sample response from the API: { "totalRecords": 9524, "size": 20, "currentPage": 1, "totalPage ...

submission of form data and automatic redirection to another page

Seeking advice on managing form submissions and page redirection. I have a landing page with a basic form, where users select criteria and are then redirected to page2 displaying tabular data and query information. When submitting the form on Page1, data ...

The JSON response may be null, yet the data flows seamlessly to the success function in

Currently, I am facing an issue with Ajax. The situation is as follows: I want to check if a user is available by typing their email address. Therefore, I have created a JavaScript function that includes an Ajax script for this purpose. Here is my code: $ ...

A code to ensure input values are always set to the maximum possible value

I recently developed a script that monitors the live value property of 3 <input> elements, correcting them if the live value is outside the specified range. However, I encountered an issue where the script automatically sets the value to the max as s ...

Create an input element using JavaScript/jQuery

Looking for some help with Javascript on a simple task. When a specific option is chosen, I want to add an input field to a div element. <select name="amount" > <option value="50">50$</option> <option value="100">100$</o ...

Utilizing JavaScript to eliminate objects from a collection and showcase a refreshed arrangement

On a simple webpage using bootstrap and js/jquery, data is fetched via ajax to create entries displayed to the viewer. The process involves: - making a request - parsing XML to create an array of objects with all the data - sorting by one property - cr ...

Is it possible to execute a specified quantity of Promises simultaneously in Nodejs?

Currently, I am working on developing a web scraping application that utilizes a REST API to gather information from multiple entities on the server. The core functionality of this application can be summarized as follows: let buffer = [] for(entity in ent ...

Exploring the intersection of JavaScript and PostgreSQL: Leveraging timezones and timestamps

I'm a bit confused about how to properly use timestamps. For example, when a user creates an article, they can choose a PublishDate, and the system also automatically stores a CreateDate. a. Should I make both PublishDate and CreateDate timestamps wi ...

How to retrieve the selected values of specific option tags using jQuery?

I have a situation where I need to select an option from a dropdown menu. Here is the code for the dropdown: <select id="customUser_id" name="customUser_id"> <option value="2" label="Friends Of Friends">Friends Of Friends</option> &l ...

Pass JavaScript variables to a PHP file with the help of AJAX

Hey there, I'm new to developing web-based applications and currently learning about AJAX. I've run into a problem while trying to make an AJAX request with user inputs as variables and fetching the same variables in a PHP file. Below is the code ...

Having trouble displaying a table accurately in React

My goal is to create a table with Material UI in React, similar to the one shown in this image: https://i.stack.imgur.com/QIV8o.png Below is the code I have written so far for this table: return ( <> <div className="main-wrapper& ...

Having issues with regEX functionality in an Angular form

I need to validate a phone number using regEX. My criteria is as follows: 10 digits alpha/numeric, where an Alpha CHAR is in the 4th position (excluding hyphens). For example: 586R410056  NNN ANN NNNN  (NNN) ANN NNNN  NNN-ANN-NNNN  (NNN) AN ...

Merging text and a JSON object to retrieve the information

Having some trouble with a JSON object and retrieving values. This is the syntax that works for getting the data I need. dataJSON.companies[0].fields.Internet.length I want to dynamically evaluate the object using a string variable, like this... var me ...

The media type provided is not supported for submitting form data to the spring server

I am facing an issue when trying to upload a file to a remote spring server through an API. Despite converting the data into form data, I keep receiving an unsupported media type error (415). Below is the HTTP post request using express: var FormData = r ...

disable full page scrolling on iOS devices

Can you achieve elastic scrolling for a single absolutely positioned div in Mobile Safari without causing the entire page to move up and down? Check out this basic example that illustrates the problem: <!doctype html> <html> <head> ...

Is there a way for me to retrieve information from a different website using a URL, similar to how Digg's submit button works

Currently, I am in the process of developing a website with the cakePHP framework. As a beginner in PHP and web programming, my goal is to implement a feature similar to Digg's submit button. This functionality would involve inputting a URL, which the ...

Is there a way to retrieve data from both JSON and a file simultaneously?

I'm trying to use JavaScript fetch API to upload a photo message with text to Discord webhook. How can I upload both my JSON data and file? var discordWebHookBody = new FormData() discordWebHookBody.append("map", map) discordWebHookBody.appe ...

Strange Scrolling Issues in Blackberry Webworks when Using Touchscreens

Within my Blackberry Webworks app designed for Smartphones OS 6, 7, and 7.1, there is a portion of code that looks like this: <div style="width:100%; height:100%; overflow:hidden;"> <div style="overflow:auto;height:100px;width:100%;"> ...

What is the best way to access the methods in the "parent" class?

I am facing a situation where I have an object with fieldsCreators that hold creator methods for each field. The dilemma is how to call the creator method inside fieldsCreators as shown below: var obj={ creator:function(ch) { .... .. ...