I'm returning an array containing dates (and other things) from an API, then looping through the array on the front end to convert them into dates
The backend uses Node.Js and queries a mySql database with the mySql module:
pool.getConnection(function(err, conn) {
conn.query('SELECT * FROM myData’, function(err, result) {
if (result) {
res.json(result);
}
conn.release();
});
});
An Angular.js front end accesses the Express API.
var _getCases = function() {
return $http.get('/api/case');
};
But the dates are all strings. Here’s an example of what's received in Angular:
[
{
id: 1,
fruit: “apple”,
createdOn: "2016-09-02T23:00:00.000Z"
},
{
id: 2,
fruit: “banana”,
createdOn: "2016-09-11T23:00:00.000Z”
},
{
id: 3,
fruit: “cherry”,
createdOn: "2016-09-13T23:00:00.000Z"
},
]
I'm converting all the dates to strings in a loop but this seems inefficient. Is there a better way?
var a = $http.get('/api/case');
for(var i in a){
a[i].createdOn = new Date(a[i].createdOn);
};
return a;
$scope
and call it when showing date in HTML. Ex. in controller$scope.getDate = function(str) { return new Date(str);};
and in HTML<span>{{getDate(fruit.createdOn)}}</span>
\$\endgroup\$forEach
ormap
to iterate over array and parse the date. \$\endgroup\$$http.get
is async. You cannot simply return the result from an async operation. \$\endgroup\$serviceName._getCases().then(function(res) { $scope.someData = res.data });
\$\endgroup\$