繁体   English   中英

使用angularjs从$ http响应中获取数据

[英]get data from $http response using angularjs

我有用Java编写的服务器,在其中创建了这样的JSON对象:

@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);
    } 
}

生成的对象为字符串( jsonPlaces.toString() )如下所示:

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

我使用下面的代码将其发送到我的Web应用程序,它使用serialize()方法。

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

这是应接收响应的angularjs代码

.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',
                    ...
                });
            });
    }; 
};

我的问题是我无法从响应中获取数据。 无论我尝试了什么,结果始终是undefined[object Object] 所以我应该如何从响应中获取数据,以便例如可以使用alert()并编写类似

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

所以我也可以在我的应用程序中使用它吗?

$http返回一个承诺,该承诺将通过一个对象进行解析,该对象不仅包含主体,还包含标头和状态。 因此,要检索您在后端创建的JSON,您可以执行以下操作:

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

然后,如果要遍历对象键,可以做几件事

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

要么

var arrayOfObjects = Object.keys(data).map(function(id){
    return data[id].position;
});
console.log(arrayOfObjects) // [{"x":220,"y":90}, {"x":210,"y":250}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM