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).

Don’t forget your dependencies – filters that need $filter

I needed to wrap angularjs’s date filter in a fairly simple manner, but I rushed it initially and skipped some very basic steps. The following error occurred.

Can’t interpolate ReferenceError: $filter is not defined

app.filter('emptyStringIfDateBefore1900', function() {
  return function(input) {
    return $filter('date')(input, 'MM/dd/yyyy');
  }
});

This is really straightforward to resolve, you just need to inject $filter.

app.filter('emptyStringIfDateBefore1900', ['$filter',function($filter) {
  return function(input) {
    return $filter('date')(input, 'MM/dd/yyyy');
  }
}]);

Ack too much going on.

Right now at work we’re doing weekly reading from Domain Driven Design Quickly.  As soon as we finish that we’ll be moving on the Evans’ Domain Driven Design book.

Those are weekly progress every friday.  Then in addition to that our Programming User Group is meeting the third tuesday of each month to go over chunks of SICP.

All of those are great reads, but it can be a bit much to keep up with at times when also making sure to get family time in and prep an AngularJS talk for Nebraska Code Camp.