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!