0

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.

Console in Firefox

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

enter image description here

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.

2
  • In your service you have bound a success function to the $http promise but then you do the same in the controller. Is the second .success not being registered perhaps? Do you get the print out of "Controller successfully got facets"? Also is the returned response from $http a string or parsed JSON? Perhaps try: $scope.facetsList = JSON.parse(response).facetsList; Commented Apr 26, 2014 at 18:19
  • Thanks #eshortie both .success functions were being registered as I could see the debug in the console from both i.e. "Controller successfully got facets" from the controller and "Success getting JSON" from the service. So both success functions were registering and firing. The root cause, per Anthony's response below, was I mis-interpreted the structure of the response from $http. Once I fixed that all the lights went green and it started to work as expected. Commented Apr 27, 2014 at 15:29

1 Answer 1

2

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;
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Anthony, that was it exactly. I was following along on a tutorial and left that in there without questioning what it was supposed to do. Now that you've pointed it out it's cleared it up for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.