简体   繁体   English

AngularJS从Spring REST API读取JSON

[英]AngularJS reading JSON from Spring REST API

I'm new to AngularJS and I'm migrating an existing Spring MVC based web app over to it. 我是AngularJS的新手,我正在将现有的基于Spring MVC的Web应用程序迁移到它。 The great thing is I am removing a lot of JS that was manipulating the JSON returned from the Spring controller(s). 最棒的是我删除了很多操作从Spring控制器返回的JSON的JS。

I can get it working fine when I manually assign JSON in the Angular controller. 当我在Angular控制器中手动分配JSON时,我可以正常工作。 My problem is when I retrieve the data from my Spring MVC controller using $http it doesn't seem to work despite the fact that I get a valid response (200) and FF is showing nicely structured JSON. 我的问题是当我使用$ http从我的Spring MVC控制器检索数据时,尽管我得到了有效的响应(200)并且FF显示了结构良好的JSON,但它似乎无法工作。

Firefox中的控制台

I can even print the JSON out in the service and see it's correct. 我甚至可以在服务中打印出JSON并看到它是正确的。

在此输入图像描述

I've gone blind looking at this now and I'm hoping it's a basic variable assignment mistake that I've made. 我现在已经盲目地看着这个,我希望这是一个基本的变量赋值错误,我已经做了。

My app.js is 我的app.js是

'use strict';

// Angular app level module which depends on controllers, and services
angular.module('WebClient', [
    'WebClient.controllers',
    'WebClient.services'
]);

Below is the Angular controller and the commented out test code is the same JSON that's returned from the Spring controller. 下面是Angular控制器,注释掉的测试代码与从Spring控制器返回的JSON相同。 When I uncomment the test code everything works as expected and Batarang shows me a nicely formatted model. 当我取消注释测试代码时,一切都按预期工作,Batarang向我展示了一个格式很好的模型。

My controllers.js is: 我的controllers.js是:


'use strict';

// K,V pairs of facets to search hits

angular.module('WebClient.controllers', []).
    controller('facetsController', function($scope, facetsAPI) {
        $scope.facetsList = [];
        $scope.mychecker = true;

        facetsAPI.getFacets().success(function (response) {
            $scope.facetsList = response.facetsAPI;
            console.log("Controller successfully got facets");
            console.log($scope.facetsList);
            console.log(response.facetsAPI);

//        $scope.facetsList = [
//            {
//                "id": "type",
//                "name": "type",
//                "facet-fields": [
//                    {
//                        "id": "contents",
//                        "count": 44008,
//                        "name": "contents"
//                    },
//                    {
//                        "id": "lessons",
//                        "count": 0,
//                        "name": "lessons"
//                    },
//                    {
//                        "id": "sentences",
//                        "count": 0,
//                        "name": "sentences"
//                    },
//                    {
//                        "id": "all",
//                        "count": 44008,
//                        "name": "All"
//                    }
//                ]
//              }
//          ]


        });
    });

The $http request in the service does retrieve the data correctly from Spring and the debug line to console.log(data) outputs the well formed JSON. 服务中的$ http请求确实从Spring正确检索数据,调试行到console.log(data)输出格式良好的JSON。 The service is the last point I see valid data. 该服务是我看到有效数据的最后一点。 After this point logging statements and Batarang don't see valid data any more. 在这一点之后,记录语句和Batarang不再看到有效数据。

My services.js is: 我的services.js是:


angular.module('WebClient.services', []).
    factory('facetsAPI', function($http) {

        var facetsAPI = {};

        facetsAPI.getFacets = function() {
            return $http({url: 'http://localhost:8080/api/facets'})
                .success(function(data, status, headers, config) {
                    // this callback will be called asynchronously
                    // when the response is available
                    console.log("Success getting JSON");
                    console.log("Status: " + status);
                    console.log(data);
                })
                .error(function(data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                console.log("Error getting JSON");
                console.log("Status: " + status);
            });
        }

        return facetsAPI;
    });

My Spring controller does all the search manipulation and facet calculation and returns JSON. 我的Spring控制器执行所有搜索操作和方面计算并返回JSON。 I've confirmed this JSON is valid on Jsonlint.com. 我已经确认这个JSON在Jsonlint.com上有效。 (I know some of the this search manipulation could be done better with Angular but we're refactoring incrementally and I'm focusing on these facets for the moment) (我知道一些搜索操作可以通过Angular更好地完成,但我们正在逐步进行重构,而我现在正专注于这些方面)


    @RequestMapping(value = "/api/facets", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public @ResponseBody String getFacets() {

    // Store all facets in a list for later conversion to JSON array
    List<Object> listOfFacets = new ArrayList<Object>();

    ...
    ...
    ...

    // Add all the facets to a single map for conversion to JSON
    Map<String, Object> outerMap = new HashMap<String, Object>();
    outerMap.put("facets", listOfFacets);

    JSONArray facetsAsJson = new JSONArray(listOfFacets);
    return facetsAsJson.toString();
}

Any help is appreciated. 任何帮助表示赞赏。

response should already be the array of facets, there's no facetsAPI property on the response, so it's actually assigning undefined to $scope.facetsList . response应该已经是facet数组, response上没有facetsAPI属性,所以它实际上是将undefined赋值给$scope.facetsList Changing response.facetsAPI to response should fix it... response.facetsAPI更改为response应修复它...

facetsAPI.getFacets().success(function (response) {
    $scope.facetsList = response;
    // ...
}

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

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