Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is transformRequest in angularjs

Tags:

angularjs

I have a code

 transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    }

I know this code is change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded". But i dont know what is syntax of it . What is obj in function . Please explain for me . Thank

like image 536
Thanh Tùng Avatar asked Oct 15 '25 19:10

Thanh Tùng


1 Answers

Transform Request is generally used for converting request data in the format which can be easily handled by server (Your Back end code).

For Example - If you want to send data with some modification in request then you can use it .

       $scope.save = function() {
    $http({
        method: 'POST',
        url: "/Api/PostStuff",
        //IMPORTANT!!! You might think this should be set to 'multipart/form-data' 
        // but this is not true because when we are sending up files the request 
        // needs to include a 'boundary' parameter which identifies the boundary 
        // name between parts in this multi-part request and setting the Content-type 
        // manually will not set this boundary parameter. For whatever reason, 
        // setting the Content-type to 'undefined' will force the request to automatically
        // populate the headers properly including the boundary parameter.
        headers: { 'Content-Type': undefined},
        //This method will allow us to change how the data is sent up to the server
        // for which we'll need to encapsulate the model data in 'FormData'
        transformRequest: function (data) {
            var formData = new FormData();
            //need to convert our json object to a string version of json otherwise
            // the browser will do a 'toString()' on the object which will result 
            // in the value '[Object object]' on the server.
            formData.append("model", angular.toJson(data.model));
            //now add all of the assigned files
            for (var i = 0; i < data.files; i++) {
                //add each file to the form data and iteratively name them
                formData.append("file" + i, data.files[i]);
            }
            return formData;
        },
        //Create an object that contains the model and files which will be transformed
        // in the above transformRequest method
        data: { model: $scope.model, files: $scope.files }
    }).
    success(function (data, status, headers, config) {
        alert("success!");
    }).
    error(function (data, status, headers, config) {
        alert("failed!");
    });
};

};

like image 56
Gautam Mishra Avatar answered Oct 18 '25 12:10

Gautam Mishra