Reputation: 87
Well, i'm having some difficult to understand the use of angular.toJson
. I completely understand that it changes to a json object...
But, how can i send this obj to the server ?
The server already gives a json obj when 'GET'
, but how use it to 'POST'
and others?
sorry, i'm new :)
Upvotes: 1
Views: 238
Reputation: 38151
You don't actually need to call angular.toJson()
yourself when posting data to a server or retrieving data from the server using the $http
service.
This is the default behaviour that Angular does for you.
From the docs:
Angular provides the following default transformations:
Request transformations (
$httpProvider.defaults.transformRequest
and$http.defaults.transformRequest
):
- If the data property of the request configuration object contains an object, serialize it into JSON format.
Response transformations (
$httpProvider.defaults.transformResponse
and$http.defaults.transformResponse
):
- If XSRF prefix is detected, strip it (see Security Considerations section below).
- If JSON response is detected, deserialize it using a JSON parser.
Upvotes: 0
Reputation: 1698
You can create factory in your app:
var app = angular.module('myApp', []);
app.factory('requestsFactory', ['$http', function ($http) {
return {
postData: function (data) {
var url = // some url to send your data
return $http.post(data, url);
};
};
}];
And now, you can post your data from controllers:
app.controller('yourController', ['$scope', 'requestsFactory', function ($scope, requestsFactory) {
...
requestFactory.postData(anyData).success(function (result) {
// if server send any response
}
...
}]);
Also you can use $http
for GET
, PUT
, DELETE
requests. Click here for more information
Upvotes: 1