Angular resource make date objects
angularjs, date, javascript
Solution
The `$resource` action object can have a property called `interceptor`, which allows you to define an `interceptor` object for this particular action (like with $http interceptors). You can define `response` and `responseError` properties for this interceptor. This way you can define some date parsing functionality for the actions the resource offers:
function parseResponseDates(response) {
var data = response.data, key, value;
for (key in data) {
if (!data.hasOwnProperty(key) && // don't parse prototype or non-string props
toString.call(data[key]) !== '[object String]') continue;
value = Date.parse(data[key]); // try to parse to date
if (value !== NaN) data[key] = value;
}
return response;
}
return $resource('/books/:id', {id: '@id'},
{
'update': {
method: 'PUT',
isArray: true,
interceptor: {response: parseResponseDates}
},
....
}
);
Hope this helps!
Problem
I'm using $resource to manipulate my data. I would like to convert dates straigt away into date objects when I fetch them. It just makes it easier to work with datepicker etc. My factory: ``` AppFactories.factory("Books", ['$resource' ,function($resource){ return $resource( "/books/:id", {id: "@id" }, { "update": {method: "PUT", isArray: true }, "save": {method: "POST", isArray: true }, } ); }]); ``` Can I create a function within the factory to convert dates from the database into a date object and vice versa when I post/update? It would be really nice to integrate it right into the factory so that I can reuse it.