angularjs - ngResource custom model actions -
i'm using ngresource handle models in ionic/angular app , i'm having trouble figuring out how/if can make custom actions on resource.
i'm storing model instances in local storage , when update record, want update local storage well. have working, i'm having copy , paste code multiple instances , keep dry.
logentry.update($scope.timelog, function(data) { // update local storage ( var = 0; < logentries.length; i++) { if(logentries[i].id == $scope.timelog.id){ logentries[i] = $scope.timelog; } }; localstorageservice.set('logentries', logentries); });
here situation update record, , after promise returns update local storage. make repeatable, how envision being possible (based on other things i've seen in other frameworks , other languages) like:
logentry.update($scope.timelog, function(data) { // update local storage logentry.updatelocalstorage($scope.timelog); });
my resource looks like:
.factory('logentry', function(config, $resource) { return $resource(config.apiurl + 'logentries/:id/', {}, { 'update': { method:'put', params: { id: '@id' } } }); })
maybe i'm missing in docs, it's pretty short , i'm not seeing way this. logentry.updatelocalstorage($scope.timelog);
possible store ngresource, or custom actions need come somewhere else? i'd keep model-related actions if possible.
you use transformresponse
method in resource definition. it's kind of hack since don't need alter response, allows preform actions returned data:
{function(data, headersgetter)|array.<function(data, headersgetter)>}
transform function or array of such functions. transform function takes http response body , headers , returns transformed (typically deserialized) version. default, transformresponse contain 1 function checks if response looks json string , deserializes using angular.fromjson. prevent behavior, set transformresponse empty array: transformresponse: []
https://docs.angularjs.org/api/ngresource/service/$resource
.factory('logentry', function (config, $resource) { return $resource(config.apiurl + 'logentries/:id/', {}, { 'update': { 'method': 'put', 'params': { 'id': '@id' }, 'transformresponse': function (data, header) { // stuff data return data; } } }); })
that way execute when response use transformrequest
method, fire on request regardless if you're getting response.
{function(data, headersgetter)|array.<function(data, headersgetter)>}
transform function or array of such functions. transform function takes http request body , headers , returns transformed (typically serialized) version. default, transformrequest contain 1 function checks if request data object , serializes using angular.tojson. prevent behavior, set transformrequest empty array: transformrequest: []
https://docs.angularjs.org/api/ngresource/service/$resource
which choose depends on usecase. using transformrequest
save localstorage, when remote down.
Comments
Post a Comment