Previously, I had a similar code that was functioning well, but for some reason, this particular section is not working as intended. The concept is simple; call the function, which in turn calls an $http
-based factory to retrieve data and return an array containing that data. Let's start with the factory:
app.factory('getSensors', ['data', function (data) {
return { get : function() {
data.get('sensors').then(function (results) {
var sensors = [];
for(var i = 0; i < results.sensors.length; i++) {
sensors.push({
'id' : Number(results.sensors[i][0]),
'name' : results.sensors[i][1],
'type' : results.sensors[i][2],
'device' : results.sensors[i][3],
'unit' : results.sensors[i][4],
'parent' : Number(results.sensors[i][5]),
'latitude' : Number(results.sensors[i][6]),
'longitude' : Number(results.sensors[i][7])
});
}
return sensors;
});
}
};
}]);
The above factory utilizes the following data
service:
app.factory('data', ['$http', function ($http) {
var serviceBase = '/api/';
var obj = {};
obj.get = function (q) {
return $http.get(serviceBase + q).then(function (results) {
return results.data;
});
};
return obj;
}]);
In attempting to call the factory, I have tried using getSensors
, getSensors.get
, and getSensors.get()
, despite knowing that some of these are incorrect. I have also experimented with various ways to structure the code, such as defining a function above the return statement and returning the array without an object (similar to how it functions in another part of my code, although I acknowledge that this might not be best practice, it is just simpler). Additionally, I replaced the for
loop with a forEach
.
Unfortunately, the value returned by the getSensors
factory consistently occurs before the completion of the $http
call, based on my console debugging. This issue persists even when the relevant code is within the callback function and after the loop. Despite spending 2 hours reviewing and rewriting this code, I am perplexed as to why this behavior is happening. It's possible that I am overlooking something obvious or inadvertently violating a fundamental Angular principle.