angularjs - Common transformResponse in factory $resource -
we using factory interact series of custom apis around common entities. however, part of need evaluate custom responses sent in headers , seems way use transformresponse. have seems working, i'm literally repeating same thing on , on in each definition. tried creating function make reusable, reference seems fail. doing wrong?
(function() { 'use strict'; angular.module('aumbills', ['ngresource']) .factory('bills', ['$resource', function($resource) { return $resource( '/ua_aumcore/bills/api/v1/bills/:billableeventi', { billableeventi:'@billableeventi' }, { getlist: { method: 'get', isarray: false, transformresponse: function(data, header, status, config, statustext) { var response = {}; if (isjson(data)) { data = angular.fromjson(data); response.data = data; } response.status = status; response.config = config; response.statustext = statustext; return response; }, url: '/ua_aumcore/bills/api/v1/bills/query/' }, getparties: { method: 'get', isarray: false, transformresponse: function(data, header, status, config, statustext) { var response = {}; if (isjson(data)) { data = angular.fromjson(data); response.data = data; } response.status = status; response.config = config; response.statustext = statustext; return response; }, url: '/ua_aumcore/bills/api/v1/customer/billparties/?partysites=:partysiteids', params: {partysiteids: '@partysiteids'} } //plus 12 more after }); }]); function isjson(str) { try { json.parse(str); } catch (e) { return false; } return true; } })();
the code broke looked identical above, put:
transformresponse: transresp(data, header, status, config, statustext),
in each definition, , function follows after isjson:
function transresp(data, header, status, config, statustext) { var response = {}; if (isjson(data)) { data = angular.fromjson(data); response.data = data; } response.status = status; response.config = config; response.statustext = statustext; return response; }
it looks defining transformresponse function want use variable, , plugging variable definition works:
(function() { 'use strict'; angular.module('aumbills', ['ngresource']) .factory('bills', ['$resource', function($resource) { var transresp = function(data, header, status, config, statustext) { var response = {}; if (isjson(data)) { data = angular.fromjson(data); response.data = data; } response.status = status; response.config = config; response.statustext = statustext; return response; }; return $resource( '/ua_aumcore/bills/api/v1/bills/:billableeventi', { billableeventi:'@billableeventi' }, { get: { method: 'get', isarray: false, transformresponse: transresp, url: '/ua_aumcore/bills/api/v1/bills/:billableeventi' }, getlist: { method: 'get', isarray: false, transformresponse: transresp, url: '/ua_aumcore/bills/api/v1/bills/query/' } //and on , forth }); }]); function isjson(str) { try { json.parse(str); } catch (e) { return false; } return true; } })();