What is the best way to display JSON data with Angular and Spring MVC?

After receiving valid JSON Data through @RestController, I am wondering if my method of displaying it on an angular jsp is correct.

Spring Controller

@RequestMapping(value="/states",
                        method=RequestMethod.GET,produces= {"application/xml", "application/json"})
                @ResponseStatus(HttpStatus.OK)
                public Object getStates() throws Exception{

                JSONObject obj = new JSONObject();
                String result= dataManager.getStates();
                obj.put("states", result);
                return obj;
  }

index.jsp

var app = angular.module('myApp', []);
function MyController($scope, $http){

    $scope.getStateDataFromServer = function() {            
        $http({method: 'GET', url: 'http://localhost:8080/states'}).
        success(function(data, status, headers, config) {
            $scope.state = data;
        }).
        error(function(data, status, headers, config) 
        });
    };
   };
</script>
</head>
<body>
<div data-ng-app="myApp">
    <div data-ng-controller="MyController">
        <button data-ng-click="getStateDataFromServer()">Get State data from server</button>
        <p>States : {{states}}</p>

Answer №1

If you want to solve this issue, consider using the following:

App.js:

var app = angular.module('myApp', []);
//Controller
app.controller("MyController", ["$scope", "$http",function($scope, $http){

 $scope.getStateDataFromServer = function() {
   $http({method: 'GET', url: 'http://localhost:8080/states'}).
    success(function(data, status, headers, config) {
        $scope.data = state;
    }).
    error(function(data, status, headers, config) 
    });
 }
}]);

Html:

<div data-ng-app="myApp">
    <div data-ng-controller="MyController">
      <button data-ng-click="getStateDataFromServer()">Get State data from    
                                                         server</button>

           <p>States : {{state}}</p> //Because $scope.data=state;
           //If you have data associated should do: {{state.myFirstData}}
    </div>
</div>

Consider trying something like:

$http({method: 'GET', url: 'http://localhost:8080/states'}).
    success(function(data){ . . .

You can simplify it first and then add status, headers, and config once it's functioning. For handling multiple states, check out ng-repeat or refer to a helpful post here.

When retrieving Json data, I typically use:

Example.js:

myApp.controller("myController", ["$scope", "$http",function($scope, $http){

  $scope.initGetRequest = function(){
    $http.get('http://localhost/myJSON.json').success(function(data){

      $scope.data=data;
    })
  }
}]);

I hope this information proves helpful.

Answer №2

Initially, your controller is not registered with the module. (I'm not sure if you just copied and pasted the code or if you wrote it in a condensed format for Stack Overflow).

Furthermore, I noticed in the controller that you have declared $scope.state:

success(function(data, status, headers, config) {
    $scope.state = data; //<- this line here
})

However, in the view, you are using {{states}} (in plural form):

<p>States : {{states}}</p>

This doesn't seem to be correct, does it?

Additional Information:
The message "The resource identified...." suggests a possible absence of Spring ContentNegotiationViewResolver or a missing @ResonpseBody annotation, along with potentially missing libraries (which I don't see in your case).

Please refer to these links:
Spring MVC error: The resource identified by this request is only capable of generating responses
and here:
406 Spring MVC Json, not acceptable according to the request "accept" headers

All aspects need to be taken into consideration (including adding JAR files, configuring annotations OR ContentNegotiationViewResolver).

Lastly, while the accept header may not be crucial, it's recommended to ensure that both accepts and content types are set correctly so that browsers can recognize themselves as accepting the json data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rendering templates using AngularJS within a Play Framework 2 project

I am currently in the process of transforming my application built on Play Framework 2.5 into a single page application using AngularJs. Here is an overview of what I was previously doing: Displaying a list of posts, utilizing Scala Template's @for ...

Issue concerning the encoding when using json_decode

I encountered an encoding problem while trying to fetch data from a third-party source. When using json_last_error(), it threw back the error message Unexpected control character found. After some research, I learned that this issue could arise from a non ...

cssclassName={ validatorState === RIGHT ? 'valid' : 'invalid' }

Is there a way to dynamically add different classes based on validation outcomes in React? My current implementation looks like this: className={ validatorState === RIGHT ? 'ok' : 'no' } However, I also need to handle cases where the ...

Mastering the ng-submit directive for AngularJS

Having an issue with my form that submits a location to Google's Geocoder and updates the map with the lat/long. When using ng-click on the icon, it requires double clicking to work properly. And when using ng-submit on the form, it appends to the URL ...

Unusual occurrences of Vuex mutations within an Electron application utilizing electron-vue framework

Currently, I am in the process of developing a straightforward task management application using Vue and Electron. My framework is reliant on the electron-vue boilerplate with Vuex store integration. The app allows users to add new items to a list (and mod ...

Ways to run a function with a delay

I'm looking to run a function at a later time, so I have written the following code: setTimeout(function(){ console.log("hi");}, 3000)); However, my issue is that I only want the message to be printed after the 3000 ms have elapsed. Can anyone as ...

Is it necessary to compile the React JavaScript project before uploading it to npm?

Hey there, I'm currently in the process of publishing a React JavaScript component on npm. I have a question regarding whether or not I need to build the project and deploy the build folder. Your input would be greatly appreciated. Thanks! ...

Issue with footer not dynamically adjusting its height when scrolling to the bottom

How can I make the footer fill the entire window when scrolling down 50px from the bottom? I attempted to animate its height, but it's not working as expected. HTML <div id="main"> ... </div> <footer> <div id="sitemap">S ...

Retrieve an HTML document from a specified URL using JavaScript AJAX methods

var $ = require('jquery'); $.ajax({ type:"GET", dataType: 'html', url: 'http://www.google.com/', success: function(res){ console.log(res); } }); The error displaying in the console is: XMLHttpRequest cannot lo ...

The JSON response from the test website contains additional characters that are causing issues with the json_decode function

Currently, I'm in the process of understanding how to transfer data between servers. I came across a test API online that contains JSON data and decided to experiment with it using the following code snippet: <?php // Initializing a CURL sessi ...

Having difficulty sending string values with Axios and FormData in Vue.js

Is there a way to send both a file input and text input in a single request using Axios and FormData in Vue.js? I've come across a solution that seems straightforward: const formData = new FormData(); formData.append('file', file); formData. ...

Tips for dynamically changing the class of a form field in jQuery when it is empty

I am currently working on a form that looks like this; <form id="myform" name="myform"> <input type="text" class="required" value="" name="qwer" /><br /> <input type="text" value="" name="asdf" /><br /> <input type=" ...

markers not included in the map

I am facing an issue with loading geographic information from a JSON file to a map using the ArcGIS JavaScript API. Currently, only the map itself is being displayed and I am unable to figure out why the points in the JSON file are not showing up on the ma ...

Utilizing jQuery or JavaScript to convert a PHP return value into an array for use in JavaScript

Is there a way to retrieve a JavaScript array from a PHP return value? For example, if a PHP script called 'makeArray.php' returns "first", "second", "third" (without the single quotes), how can I use this array in JavaScript to alert "second"? ...

Use the map function to find the highest number within each array

function each(collection, func) { if (Array.isArray(collection)) { for (var i = 0; i < collection.length; i++) { func(collection[i], i); } } else { for (var key in collection) { func(collection[key], key); } } } functi ...

Encountered an error while trying to initiate MongoDB using dpd-d

Trying to kick off a Deployd application, I encountered some hurdles. Upon entering dpd-d in the terminal, an error message popped up: deployd v0.6.11 startup failed... Failed to initiate MongoDB Seeking to debug the issue by typing 'DEBUG=* dpd&apo ...

What is the best way to achieve consistent alignment in Javascript?

I have been attempting to incorporate HTML code within JavaScript for alignment and styling. Despite searching on Google for 3 to 4 days, I have not found a suitable answer yet. What exactly am I looking for? Here is a snippet of my JavaScript code: funct ...

using async.waterfall with async.apply

Here is a code snippet that I am working with: async.waterfall([ // Read directory async.apply(fs.readdir, '../testdata'), // Load data from each file function(files, callback) { async.each(files, loadDataFromFile, callback); } ], ...

Exploring Next.js with getServerSideProps

My code has a warning from the console attached. I would appreciate it if someone could help me identify the problem... When I use the "data" hardcoded as props, I can display them in the components, but when I try to fetch from an API, I can retrieve the ...

Maintain the state of the previous page in Vue to ensure continuity

Currently in the process of creating a small PWA to simulate an Android app, I have discovered Vuejs. However, I encountered an issue that has proven difficult to resolve. While scrolling through lists on the homepage for movies, TV shows, or news, clicki ...