简体   繁体   中英

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. The great thing is I am removing a lot of JS that was manipulating the JSON returned from the Spring controller(s).

I can get it working fine when I manually assign JSON in the Angular controller. 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.

Firefox中的控制台

I can even print the JSON out in the service and see it's correct.

在此输入图像描述

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

'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. When I uncomment the test code everything works as expected and Batarang shows me a nicely formatted model.

My controllers.js is:


'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. The service is the last point I see valid data. After this point logging statements and Batarang don't see valid data any more.

My services.js is:


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. I've confirmed this JSON is valid on 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)


    @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 . Changing response.facetsAPI to response should fix it...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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