ngResource and JSON Encoded Dates

Most of the things I work on are internal business applications so I deal with dates a lot. One of the common problems is that often you’ll get something like the following in a variable:

“/Date(1398142800000)/”

Some JSON encoders format dates this way since there is no type safety in JSON and this gives a great indicator as to what type the value is. It does give a problem of thinking the date is a string by default though. To get around this when using Angular’s ngResource you can use the transformResponse property.

app.service('BusinessObjects', [
  '$resource', function($resource) {
    return $resource('/BusinessObjects/:action/:id', null, {
      'query': {
        method: 'GET',
        params: { action: 'query' },
        isArray: true,
        transformResponse: function businessObjectsTransformResponse(data, headers) {
          data = JSON.parse(data);
          for (var i = 0, len = data.length; i < len; i++) {
            if (typeof(data[i].ShipDate) != "undefined") {
              data[i].ShipDate = new Date(data[i].ShipDate.match(/-?\d+/)[0] * 1);
            }
          }
          return data;
        }
      }
    });
  }
]);

In our controller we can use this by passing in BusinessObjects as a dependency and then using it.

app.controller('businessObjectsController', ['$scope', 'BusinessObjects', function($scope,BusinessObjects){
  $scope.businessObjects = BusinessObjects.query();
}]);

For more information on resources, read the docs.

 

(In case you’re wondering, the reason for the action param is that I have to use asp.net mvc for this which doesn’t allow multiple actions for a single endpoint based on HTTP verbs. The better fit when using aspnet and angular if you’re building a SPA is to use Web API).

Leave a Reply

Your email address will not be published. Required fields are marked *