Sefinek Sefinek - 4 years ago 109
AngularJS Question

get data from $http response using angularjs

I have server written in Java, where I create JSON objects like this:

@Override
public void serialize(Net net, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
try {
Set<Place> places = net.getPlaces();
Set<Transition> transitions = net.getTransitions();
JSONObject jsonPlaces = new JSONObject();
for (Place p : places)
{
String id = p.getId();
double xCoord = p.getxCoord();
double yCoord = p.getyCoord();
JSONObject jsonPosition = new JSONObject();
jsonPosition.put("x", xCoord);
jsonPosition.put("y", yCoord);

JSONObject jsonPlace = new JSONObject();
jsonPlace.put("position", jsonPosition);
jsonPlaces.put(id, jsonPlace);
}
jg.writeRawValue(jsonPlaces.toString());

} catch (Exception ex) {
throw new IOException("...", ex);
}
}


The resulting object as string (
jsonPlaces.toString()
) looks like this:

{"id01":{"position":{"x":220,"y":90}},"id02":{"position":{"x":210,"y":250}}}


I send it to my web application using the code below, it uses the
serialize()
method..

@POST
@Path("/blindLayout")
@Consumes(MediaType.APPLICATION_JSON)
public Net blindLayout(Net net) throws Exception {
.
.
return net;
}


And here is the angularjs code that should recieve the response

.factory('Layout', function ($http, Notification, AnalysisConfig) {
layoutPrototype.performLayout = function (net, options, defered) {

if (net) {
var address = AnalysisConfig.serverAddress + AnalysisConfig.resourceURI + AnalysisConfig.resources.blindLayout;
$http.post(address, JSON.stringify(net), {timeout: AnalysisConfig.timeout})
.then(function (response) {
var data = response;
},
function (response) {
Notification.error({
title: 'Communication error',
...
});
});
};
};


My problem is that I canĀ“t get data from the response. No matter what I tried, the result is always
undefined
or
[object Object]
. So how should I get data from response so I can for example use
alert()
and write something like

id01 (value of x, value of y)
id02 (value of x, value of y)
...


so I can also use it in my app?

Answer Source

the $http returns a promise that's resolved with an object that contains more than just the body but also headers and status. So to retrieve the JSON you created on a backend you can do:

$http.post(address, JSON.stringify(net), {timeout: AnalysisConfig.timeout})
    .then(function (response) {
        var data = response.data;
    },

and then if you want to iterate over object keys you can do few things

for(var id in data){
  console.log(data[id]) //{"position":{"x":220,"y":90}}
  console.log(data[id].position) //{"x":220,"y":90}
}

or

var arrayOfObjects = Object.keys(data).map(function(id){
    return data[id].position;
});
console.log(arrayOfObjects) // [{"x":220,"y":90}, {"x":210,"y":250}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download