Ted Herrlich Ted Herrlich - 3 months ago 11
reST (reStructuredText) Question

Angular REST returning Syntax error on JSON parse

I am getting an error "syntax error JSON parse unexpected end of data at line 1 column 1 of json data". The RESTful service is runnning, a straight test returns valid json data (verified at http://jsonlint.com/)

[{"id":2,"name":"Flourescent Penetrant Inspection","description":"The fluorescent penetrant inspection process.","abbreviation":"FPI","tempId":null,"processType":"INSPECTION","indicationTypes":[{"id":1,"name":"Crack","description":"An identified crack on the piece.","abbreviation":"","tempId":null,"groupName":"","markupType":"LINE","useSizeDescription":true,"sizeDescription":"<= 1 in.::> 1 in.","rejectReason":"Crack","defaultDisposition":"MRB"},{"id":2,"name":"Inclusion","description":"An identified inclusion on the piece.","abbreviation":"","tempId":null,"groupName":"","markupType":"DOT","useSizeDescription":false,"sizeDescription":"","rejectReason":"Inclusion","defaultDisposition":"REWORK"}]},{"id":4,"name":"CMM","description":"The CMM process.","abbreviation":"CMM","tempId":null,"processType":"INSPECTION","indicationTypes":[]}]


The error in the HTTP response, yet it is returning a 200 message. The angular app is seeing it as an empty array. Any ideas?

The applicable part of the Controller is:

indicationTypeController.constant("indicationTypeUrl", "http://localhost:8080/services/api/indication-types.json");

indicationTypeController.controller('indicationTypeController', function ($scope, $http, $resource, indicationTypeUrl) {

$scope.indicationTypeResource = $resource(indicationTypeUrl+":id", { id: "@id" },
{ 'create': {method: "POST"}, 'update': {method: "PUT"}
});

$scope.listIndicationTypes = function () {
$http.get(indicationTypeUrl)
.success(function(data){
$scope.indicationTypes = data;
});

//$scope.indicationTypes = $scope.indicationTypeResource.query();

}
. . . .


As you can see I am currently using a $http.get, I also tried a query().

Any

Answer

Usually, the $http promise returns an object that contains the headers and the data. In your success handler for the $http, you have

    $http.get(indicationTypeUrl)
        .success(function(data){
            $scope.indicationTypes = data;
        });

I'm pretty sure that data is the full response and you need to get the specific data by using the data property of this object. Therefore, this would become the following:

    $http.get(indicationTypeUrl)
        .success(function(data){
            $scope.indicationTypes = data.data;
        });

In other implementations, instead of the passed in parameter being called data, it's usually called result, so that you can reference the contained data like result.data instead of data.data

The other thing to make sure of is that the Content-Type is set appropriately between the server and client. If it's not application\json you'll probably run into issues.