Getting JsonArray data from Jersey using Angular js - angularjs

I am writing simple application with REST in the backend and Angular as frontend. And now I cant make them talk properly.
My Jersey class gets some data from database make JSONArray from it and send it to response to get.
#GET
#Path("{userID}")
#Produces(MediaType.APPLICATION_JSON)
public String getLearningList(#PathParam("userID") int userId)
{
SqlConnector con = new SqlConnector();
List<String> list = con.getUsersLearningList(userId);
JSONObject jObj = new JSONObject();
jObj.put("list", list);
JSONArray jArray = jObj.getJSONArray("list");
return jArray.toString();
}
In Angular I am using angular-resourse to get data from REST and even I made isArray: true I am getting this error:
Error in resource configuration for action `get`. Expected response to contain an object but got an array
Here is my angular
myApp.factory('GetDataService', ['$resource', function($resource){
return {
getData: function(url)
{
return $resource(url,{},{
query: {
method: 'GET',
params: {},
isArray: true
}
})
}
}
}]);
SqlConnector is just my class which work with database.
I am completely new in Angular. Thank you in advance!

Related

how i can send post data array angular and get data on api laravel

i have code like it on angular
my array :
[{"kode":"123","nama":"satu dua tiga"},{"kode":"321","nama":"tiga dua satu"}]
$http({
method: 'POST',
url: 'api/insertCustomerArr',
data: myarray
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
and how i can get this data on controller laravel and how i can looping ?
public function insertCustomerArr(Request $request)
{
echo count($request);
exit;
}
this code result count 1, how i can get data?
You can check using
return $request->all();
this will return all the data you posted from angular request
Laravel $request object has a request property inside of it.
So that basically $request->request->all(); should contain all the data that came from angular.

getting null using angular post

I'm having some problem using AngularJS post. I keep getting null from the server in my Angular success method even though server returns "success".
Here's my post req:
$http({
url: "/room/addUserInfo",
responseType:'json',
method: "POST",
data: json,
headers: {
"Content-Type": "application/json"
}
})
.success(function(data){
var a = data;
})
.error(function(data){
var a = data;
});
And this is my backend (Spring MVC):
#RequestMapping(value="/addUserInfo", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody String addEmployee (#RequestBody User user){
Database database = new Database(username, pass, dataName, port);
Connection connection = null;
try{
connection = database.connect();
database.addUserInfo(connection, user);
}catch(Exception e){
e.printStackTrace();
return e.toString();
}
return "success";
}
Just to mention, everything gets stored in the database, so the code is working and server returns "success" it's just that the success method on the client gets null every time. But, when I'm using Angular get method everything works.
Anyone had this kind of problem or knows how to fix this?
Thank you

Angular $resource and webApi

I am using webApi and have generated the model using entityframework the overload method of the GET(int id) I am trying to call that using the query of the $resource
I am trying to pass an optional parameter to a call using the $resource but get the error [$resource:badcfg] I have had a google and people say add
{
'get': {method: 'GET'},
'query': {method: 'GET', isArray: true}
}
into the function, so I have tried this: but still have no luck.
function minorResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/minorworks/:id",
{
'get': {method: 'GET'},
'query': {method: 'GET', isArray: true}
});
}
Would you use 2 separate methods or can the above function be made to work?
For completness here is my Controller call
minorResource.query({id: vm.seachCriteria}, function (data) {
//console.log(data);
vm.minorWork = data;
});
Note that query is used to retrieve an array of objects and get is used to retrieve a single object. That means that with a get you usually sent the id of the object to the API.
So in your case:
var minorWorksResource = $resource(appSettings.serverPath + "/api/minorworks/:id");
// Note that query returns an array.
var works = minorWorksResource.query(function() {
var firstWork = works[0];
});
// Note that we pass an ID that will be fetched in the query string.
var singleWork = minorWorksResource.get({id: 123}, function() {
});
And the WebAPI part:
[RoutePrefix("api/minorworks")]
public class MinorWorksController : ApiController {
public IHttpActionResult Get(int id) {
var singleWork = null;
// Retrieve a single item;
return Ok(singleWork);
}
public IHttpActionResult Get() {
var workList = null;
// Retrieve the whole list.
return Ok(workList );
}
}

How to send multiple parameters in AngularJS $http.post to Web API controller action method

How to send multiple parameters in an angularjs $http.post to web api controller action method.
Below is my code.
AngularJS code
var complexObj = { prop1: "value", prop2: "value" };
var id = 100;
var data = { id: id, complexObj: complexObj };
$http({
method: 'POST',
url: 'http://localhost/api/WebApiController/MethodName',
data: data
}).success(function (data, status) {
//do something...
});
$http.post('http://localhost/api/WebApiController/MethodName', data)
.success(function (data, status) {
//do something...
});
Web API controller
[RoutePrefix("api/WebApiController")]
public class WebApiController: ApiController
{
[Route("MethodName")]
public ReturnValue WebApiAction(string id,ComplexObj complexObj)
{
// process request and return data...
}
}
I am getting below response message in fiddler.
{ "message": "No HTTP resource was found that matches the request
URI 'http://localhost/api/WebApiController/MethodName'.",
"messageDetail": "No action was found on the controller
'WebApiController' that matches the request." }
When I send the complexObj alone, its hitting the web api,but all properties are null or set to default values.
What am I doing wrong? How can I send two or more parameters(both complex objects and string/int) in $http.post? Any help is much appreciated.
Web API doesn't support multiple post parameters in this way.
Your best bet is to roll up Id into ComplexObj and post it as a single parameter.
complexObj.id = id;
var data = complexObj;
Update your signature to take just a single object.
[Route("MethodName")]
public ReturnValue WebApiAction(ComplexObj complexObj)
{
// process request and return data...
}
If you absolutely want to be able to post data like this, consider Rick Strahl's post on creating a custom parameter binder.

Ajax Post containing list of objects to Spring MVC Controller

How do i post a list of objects from javascript to Spring MVC Controller? I can post arrays, objects, but not a combination of the 2. This is my code below.
Javascript:
var utilData = getTableData();
// Sending data over to server
console.log(utilData);
$.ajax({
url: "saveUtilData2.html",
type: "POST",
contentType: "application/json",
dataType: "json",
data: {utilArray: utilData},
success: function(data){
alert("save was sucessful");
},
error: function(){
alert("Save wasn't successful");
}
});
Spring Controller (tried changing utilData to String[] and object[] ... both didnt work:
#RequestMapping(value="/saveUtilData2.html", method=RequestMethod.POST)
public ModelAndView saveUtilData2(#RequestParam("utilArray") String[] utilData, HttpServletRequest request)
{
System.out.println("Util Save Data method 2");
ModelAndView mv = new ModelAndView("util");
return mv;
}
Use #Requestbody instead of Requestparam

Resources