Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - transformRequest is not getting called on $resource

Tags:

angularjs

I am adding a pair of actions to an AngularJS resource, but when I invoke the action, my transformRequest function is not getting called:

    var _resource = $resource('api/NewItem/:id',
    { id: '@id' },
    {
        create: {
            method: 'POST',
            transformRequest: function (data, headersGetter) {
                var result = JSON.stringify(data.productIntro);
                return result;
            }
        },
        update: {
            method: 'PUT',
            transformRequest: function (data, headersGetter) {
                var result = JSON.stringify(data.productIntro);
                return result;
            }
        }
    });

If I add the function globally on the app, it works:

var newItemApp = angular.module('newItemApp', ['ngResource'])
.config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data)
    {
        if (data === undefined) {
            return data;
        }
        var result = JSON.stringify(data.productIntro);
        return result;
    };
});

What I need to do is remove the root element from any POST or PUT action because the default model binding in Web Api does not bind a json object when that object has a named root.

like image 307
Stuart Avatar asked Aug 29 '13 13:08

Stuart


1 Answers

transformRequest is supported since AngularJS 1.1.2. If you use early version, you need to add it to $httpProvider.

like image 96
zs2020 Avatar answered Sep 17 '22 23:09

zs2020