javascript - angularjs $resource class-level callbacks, or post-processing -
i have $resource api return data needs cleaned before going presentation layer. specifically, it's .net returning date objects in lovely '/date(...)/' format.
i don't want have write callback every time call .query() or .get(). there way extend resource callback gets called upon rest methods update instance's properties, or adding sort of $watch gets fired when date property changes? happen every instance of $resource.
angular.module('myappservices', ['ngresource']) .factory('participant', ['$resource', function ($resource) { var res = $resource('api/url/participants/:id', { id: '@id' }); // doesn't work, kinda this? res.prototype.$watch(this.fieldname, function(newval, oldval) { if (needscleaning(newval.fieldname) { this.fieldname = cleanupfield(newval); } }; });
ah-ha, found way around , leave here. in version 1.1.2 added support passing $http.config options $resource. naturally, cdn i'm using doesn't have recent enough version of angular-resource.js, switching cdns solved that.
i used transformresponse option modify data comes back.
angular.module('myappservices', ['ngresource']) .factory('participant', ['$resource', '$http', function ($resource, $http) { var res = $resource('api/url/participants/:id', { id: '@id' }, { save: { method: 'post', transformresponse: $http.defaults.transformresponse.concat([ function (data, headersgetter) { data.fieldname = yourdateparsingfunction(data.fieldname); return data; } ]) } }); i'm adding transformer on $httpprovider's transformresponse, deserialization, etc.
Comments
Post a Comment