Making a $http.put with query param, path param and body - angularjs

I am trying to call a API service something like url/1?param1=&param2=
it also expects a body(request payload) using $http.put.
Can anyone tell me how to do it in a efficient way?

Just don't use param: use data: in your config object.

You can pass both parameters (in the query string) and a request body like this
$http({
url: "url",
method: "put",
params: {
param1: value1,
param2: value2
}
data: JSON.stringify(objectContainingBody)
}).then(.....)

You could do something like this :
$http.put('url/path', payload, { params: { param1: 1, param2: 2 } }).then(
function(response) {
// access data with response.data
},
function(error) {
// do something with the error
}
);
If you need to convert your payload to json : angular.toJson(payload).
You can look at AngularJS $http.put for reference.

Related

angular POST not working with servlet

I am trying to use angularjs POST (or even GET) to a servlet with the following:
var json = { hello: "world" }
var deffered = $q.defer();
$http({
method: "POST",
url: url,
headers: { "Content-Type" : "application/json" },
request: JSON.stringify(json)
}).then(data) {
if(data.data) {
deferred.resolve({
response : data
});
)
})
return deffered.promise;
within the servlet, simple:
String val = request.getParameter("request")
it never seems to see it
I have tried:
data: JSON.stringify({ request: json })
data: { request: json }
"request" : JSON.stringify(json)
etc
if I comment out the getParameter and just return a generic value using Gson
JsonObject json = new JsonObject();
json.addProperty("This", "works");
response.getWriter().print(new Gson().toJson(json));
that comes back fine so is there something within the angular POST I am doing wrong here? I have also tried using "GET" instead but same result.
EDIT: I would like to understand POST method and the "proper" way to get the data from the json object if getParameter is wrong please~
getParameter() returns http request parameters, you should add this params by using :
params: JSON.stringify(json)
Not with
request: JSON.stringify(json)
Take a look in params in get and params in post.

$resource send data in get insted of post

I am try to post data form $resource in angular js project. It is my code in factory
deletemenu: function(menudata ) {
return $resource(url+'/menu/delete', {}, {
delete_menu: {
method: 'POST',
params: {
entityType : menudata.entityType ,
sellerId : menudata.sellerId ,
menuId : menudata.menuId ,
parentMenuIds : menudata.parentMenuIds ,
menuItemId : menudata.menuItemId
},
isArray: false
}
}).deletemenu();
}
I declare method POST but the request is send as a query string not the post request. It send as a
URL+"menu/delete?entityType=I&menuId=25&menuItemId=20&parentMenuIds=4&sellerId=1"
How I send these data as a POST method.
I think this should work better for you
return $resource(url + '/menu/delete', null, {
delete_menu: {method: 'POST'}
}).delete_menu(menudata);
Here, I'm passing in the menudata as the first argument to the non-GET "class" action delete_menu which will use it as postData.
The objects returned by $resource are much more flexible than what you're using here. It looks like you should be able to make your service / factory much neater by returning the $resource instance instead of these individual functions. For example
.factory('menuFactory', function($resource) {
var url = 'whatever';
return $resource(url, null, {
delete: {
url: url + '/menu/delete',
method: 'POST'
} //, other actions here
});
})
Then you can call it with
menuFactory.delete(menuData)

Posting to a REST interface

need to define the name as ID in the URL and need to post an object containing data.
$scope.dvModel.naam is the name that acts as the ID.
filteredObject is the object containing the data, obviously.
This is how I call the service, seems ok according to some examples.
saveDVservice.query($scope.dvModel.naam, filteredObject);
This is the actual service.
.factory('saveDVservice', ['$resource', 'CONSTANTS', function($resource, CONSTANTS) {
'use strict';
return $resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
}]);
This is what I see in my network tab at Query String Parameters:
0:A
1:D
10:n
11:h
12:i
13:l
14:f
15:e
2:A
3:C
4:
5:P
6:a
7:n
8:n
9:e
Which is the name, but looks like an array.
Request Payload contains the actual object in correct order.
Can one give me some guidance on how to handle this?
As I understand, you want to put $scope.dvModel.naam into URL and you want filteredObject to be a request payload. Then you need an object that contains everything that's in filteredObject and additionaly under the key name a value equal to $scope.dvModel.naam.
Also, the definition of your resource probably should change - in second argument $resource requires you to tell it the way of extracting URL data from given object:
$resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {name: '#name'}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
Unfortunately, $resource isn't the best $http wrapper to use when your payload data is separated from URL data. Maybe it would be better to wrap the filteredObject data in payload in some other object? Then your $resource object would be much nicer, like {name: ..., data: {"0": "A", "1": "D", ...}}
Since default action for query is {method: 'GET', isArray: true}, I'd leave that be and use another default, save instead. That should work out-of-the-box.
app.factory('DVService', function ($resource) {
return $resource(CONSTANTS.REST_BASE_URL + '/dv', {name: '#name'}, {});
});
.
app.controller('MainCtrl', function ($scope, DVService) {
var postData = {
name: 'name',
fooProp: 'foo',
barProp: 'bar'
};
// save/post
DVservice.save({dv: postData}).$promise.then(function (response) {
console.log(response);
});
//query/get
DVService.query({name: 'name'}).$promise.then(function (response) {
console.log(response);
});
});

angularJs $http. cannot revice params from request

angularjs code:
$http({
method: 'POST',
url:'/hello/rest/user/test',
data: {user: 'aaaaa'}
});
Server code:
#POST
#Path("/test")
public Response merge(#Context HttpServletRequest request) {
System.out.println(request.getParameter("user"));
if (request.getParameter("user") == null) {
return Response.status(Status.BAD_REQUEST).build();
}
return Response.ok().build();
}
request.getParameter("user") is a null. I cannot revice a parameter by this way.
If you want to use request parameter, you need to pass the data as
$http.post('/hello/rest/user/test', {
user : 'aaaaa'
}, {
headers : {
"Content-Type" : 'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest : [function(data) {
return angular.isObject(data)
? jQuery.param(data)
: data;
}]
});
Also read this question
You need to look at the body rather than for the post parameter...
You may not be receiving POST parameters.
You are receiving a body that looks like this {"user":"aaaaa"} and you need to parse that JSON response.

Sending array as querystring parameter in senchatouch2

How to send Arrays as querystring parameters in Ajax request using POST methos to access a third party webservice..
Kindly provide sample code ..
While v use POST method to send parameters in SenchaTouch2 use jsonData instead of params in Ajax Request like,
Ext.Ajax.request({
url:'',
method:'POST',
disableCaching:false,
headers: {
'Accept':'application/json',
'Content-Type':'application/json'
},
**jsonData**: {
FirstName:fname //{"FirstName":["Sam","paul"]}
},
success: function(response)
{
console.log(response.responseText);
},
failure: function(response)
{
console.log(response.responseText);
}
});
This is the way I usually do it
...
params: {
array: Ext.encode(['1', '2', '3'])
},
...
Hope this helps

Resources