Restangular PUT request to update 2 Objects - angularjs

I have 2 classes on Server side.. MyClass1 and MyClass2..
Im creating a JSON object..
var myclass1 = {name:'xyz', id:16};
var myclass2 = {name:'abc', id:17}
and using restangular..
Restangular.one('some url').customPUT({var1:myclass1 , var2:myclass2 });
Im using spring framework to create my REST Services
#RequestMapping(value = "/someurl", method = RequestMethod.PUT) <br>
#ResponseBody
public void someMethod(#RequestBody MyClass1 var1, #RequestBody MyClass2 var2) {
//some code
}
This is the scenario...
But I had read a post on stackOverflow that for 1 request body we can pass (put request) only 1 object.. If so then what is the alternate way...
I can send MyClass2 object through request param (there is an annotation #RequestParam)
ex. Restangular.one('some url').customPUT({var1:myclass1 }, {}, {var2:myclass2 }, {});
But again this gets appended to my URL and i dont want to change my URL..
Please help. Thnx..

Related

Passing String from angular to Spring using #Requestbody

I am working on a project using angularjs+springboot. Am trying to send email via my application using spring-boot-starter-mail. The message and object of the email are written by the user in a form. what I want to do is to get the message and object values in my RestController using #RequestBody.
the function in my service.js
// send mail
var sendMail = function(id, objet, msg) {
var deferred = $q.defer();
$http.post(urlBase + id, objet, msg).then(
function(response) {
deferred.resolve(response.data);
}, function(errResponse) {
console.error('Error while sending email');
deferred.reject(errResponse);
});
return deferred.promise;
}
the method in my restContoller
#RestController
public class EmailController {
#Autowired
private JavaMailSender javaMailSender;
#Autowired
UtilisateurService service;
#RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public ResponseEntity<Void> sendMail(#PathVariable("id") int id, #RequestBody String objet,
#RequestBody String msg) {
Utilisateur currentUser = service.findById(id);
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(currentUser.getEmailUtil());
message.setSubject(objet);
message.setText(msg);
javaMailSender.send(message);
return new ResponseEntity<Void>(HttpStatus.OK);
}}
This throws this exception :
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Void> com.sla.utilisateur.controller.EmailController.sendMail(int,java.lang.String,java.lang.String)
How can I fix it?
thank you,
Your usage of $http.post is not correct. You should have a look at the AngularJS POST documentation. $http.post arguments are the following:
post(url, data, [config]);
AngularJS sends the data by default in JSON. So you should send the request using the following statement (for example):
$http.post(urlBase + id, {subject:objet, body:msg})
And in your controller you should define only one #RequestBody maps for the ease of the example to a Map (You could change it to a POJO. ):
#RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public ResponseEntity<Void> sendMail(#PathVariable("id") int id, #RequestBody Map<String,String> msg) {
Utilisateur currentUser = service.findById(id);
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(currentUser.getEmailUtil());
message.setSubject(msg.get("subject");
message.setText(msg.get("body"));
javaMailSender.send(message);
return new ResponseEntity<Void>(HttpStatus.OK);
}}

Angular: How to send object through $http.get?

customerLogin is object that I want to send to my service.
I do not want to use query string and do not want parameters separately.
Below is the code:
var config = {
customerLogin : { // object I intend to send
'EmailID': $scope.existingCustomer.email,
'PhoneNumber': $scope.existingCustomer.phoneNumber,
'Passkey': $scope.existingCustomer.password
}
}
$http.get(existingCustomerUrlConstant, config).
In webapi, i have below code:
[HttpGet]
// customerLogin object i want to receive here
public CustomerLogin GetCustomer(CustomerLogin customerLogin)
{
GetCustomerDAL getCustomerDAL = new GetCustomerDAL(customerLogin);
return customerLogin;
}
customerLogin is null here.
How can i receive object here from Angular service call?
Using POST method is the right call. As I stated in the comment.

unable to pass complex objects to webapi from angularjs

I'm using below code to post data to webapi controller but complex data objects are coming as null in the API controller.However, if i pass object at a time i'm seeing results meaning it is sending over the flat objects but not complex objects.Can anyone please guide me what wrong i'm doing here or is there any other way to do this??
below are the data objects and code snippet that i'm using:
Models:
var portfolio={
Accounts:{accountnumber:'',
SSN:'',
..almost 15 fields in this object},
Investments:{ID:'',
totalamount:'',
etc..here also we have more than 10 objects}
Foo: {F1:'',F2:'',F3:''...}
Foo1: {F11:'',F12:'',F13:''...}
}
Angular service:
var get=funtion(portfolio){
return $http.post('/api/values',
JSON.stringify(portfolio),
{
headers: {
'Content-Type': 'application/json'
}
}
)
}
webapi controller:
public class ValuesController : ApiController
{
[HttpPost]
public User Post([Frombody]portfolio model)
{
//logic here
}
}
Json is the http.post() default content type, so there is no need to neither specify that, nor stringify you object.
Assuming you are posting a valid json object, this should suffice:
var get = funtion(portfolio){
return $http.post('/api/values', portfolio);
}

Doing a GET passing a complex object with angular

I am using AngularJs and Resources module. I want to do a GET to obtain an object.. to do this GET I do not have to pass simply the ID to the server, but I should pass a complex object with different properties and values..
Here the code I am using:
$scope.getActivationStatus = function (event) {
event.preventDefault();
if ($scope.segui_attivazione_form.$valid) {
$scope.activationStatus =
new SeguiAttivazioneService
.seguiAttivazione()
.$get(
{
request: $scope.activationStatus
}, function () { });
}
};
On server side I have:
[HttpGet]
public IHttpActionResult GetActivationStatus(MyComplexObject request)
{
//I will do something here later...
return Ok();
}
The problem is that "request" arrive on server equals to NULL...
I have solved the problem passing two strings to the server... in this way:
$scope.getActivationStatus = function (event) {
event.preventDefault();
if ($scope.segui_attivazione_form.$valid) {
$scope.activationStatus =
new SeguiAttivazioneService
.seguiAttivazione()
.$get(
{
codiceFiscale: $scope.activationStatus.CodiceFiscale,
codiceRichiesta: $scope.activationStatus.CodiceRichiesta
}, function () { });
}
};
And server side:
[HttpGet]
public IHttpActionResult GetActivationStatus(string codiceFiscale, string codiceRichiesta)
{
return Ok();
}
In this way everything works... but I don't like this solution because I will have more than two input...
And this is a get, not a post (not a save, an update)...
How can I pass a complex object doing a GET?
Thank you...
It's best to use the POST method if you want to send data in the body of the request. While it's possible with Angular, some servers might ignore the body of GET requests.
This approach allows to send complex objects with arrays and sub objects:
Angular:
$http({
url: '/myApiUrl',
method: 'GET',
params: { param1: angular.toJson(myComplexObject, false) }
})
C#:
[HttpGet]
public string Get(string param1)
{
Type1 obj = new JavaScriptSerializer().Deserialize<Type1>(param1);
...
}
This is not an elegant solution but it works using HTTP GET:
$http.get(url + "?" + $.param(obj).replace(/%5b([^0-9].*?)%5d/gi, '.$1'))
It converts the complex object into a string with dot notation to define levels. Most of the server side frameworks like ASP.NET Core can bind it to complex objects.
This is an example of the string I send for a complex object:
StartDate=2021-06-11&EndDate=2021-06-11&TimeRange.TimeFrom.Time=07%3A00&TimeRange.TimeFrom.TimeFrame=AM&TimeRange.TimeTo.Time=10%3A00&TimeRange.TimeTo.TimeFrame=AM
Request body can only be sent by POST. With get you could at best URL Encode the OBJECT and then send it as query string params. But thats not the best solution to post some data to the server

Using Angular ng-resource with multiple query parameters

I'm trying to send a request to the server with 4 parameters. It seems to work with less than 4, but I cannot get it to work with 4 or more.
Here are the snippets:
historyy: $resource('/history/:user.:item.:count.:cost', {
user: '#userr',
item: '#itemm',
count: '#countt',
cost: '#costt'
}
Calling RestService:
RestServices.historyy.get({userr: "Asd",itemm: $scope.item.id,countt: amount,costt: '0' });
When I execute this, the URL looks like this:
http://localhost:8080/history/...?costt=0&countt=6&itemm=1&userr=Asd
Why is it adding these crazy (...?) ?. When I remove one of the parameter (no matter which one) it works properly.
You can use query (see: doc)
Resource
$resource('/history/');
Call
RestServices.historyy.query({user: "Asd", item: $scope.item.id, ...}, function(results) {
//on success
});
Result
/history?user=Asd&item=ExampleItem...
Spring REST Controller
#RestController
#RequestMapping(value = "/history", produces = MediaType.APPLICATION_JSON_VALUE)
public class SomeRestController {
#ResponseBody
#RequestMapping(method = RequestMethod.GET)
#JsonView(View.List.class)
public List<SomeThing> getSomething(
#RequestParam(value = "user", required = true) String user,
#RequestParam(value = "item", required = true) String item, ...) {...}
You can find more information here: Using $resource.query with params object

Resources