Guide on retrieving information from Spark and showcasing it through Angular

Trying to navigate the world of Spark framework and AngularJS as a beginner, I set out to create a basic REST application. However, I hit a roadblock when it came to retrieving data from the server and displaying it using Angular.

My initial task was simple:

@Data
public class Todo {

private String title = "foo";
private String description= "bar" ;
}

To display the todo in the browser, I responded to the get request with a JSON object.

get("/tasks", (request, response) ->  {
   response.type("application/json");

   Todo todo = new Todo();
   ObjectMapper mapper =  new ObjectMapper();
   mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
   String data = mapper.writeValueAsString(todo);
   return data;
});

The Angular portion is structured as follows:

(function() {
   var app = angular.module('todoapp', []);

   app.controller('TaskController', ['$http', function($http) {
       var store = this;
       store.tasks = [];

       $http.get('/tasks').success(function(data) {
           store.tasks = data;
       });
   }]);

})();

And here's the index.html :

<ul ng-controller="TaskController as taskCtrl">
   <li ng-repeat="task in taskCtrl.tasks">{{task.title}}, {{task.description}}</li>
</ul>

Upon running Spark and navigating to http://localhost:4567/tasks in the browser, I only see the JSON representation:

{
"title": "foo",
"description": "bar"
}

Where could I be going wrong?

Answer №1

When writing your Spark code, you have set up a '/tasks' endpoint that you are trying to access with your Angular code. However, when running this in the browser, you are only hitting the '/tasks' API endpoint and receiving the expected response. To resolve this issue, you must create a new endpoint in Spark that will provide the necessary HTML and JavaScript code.

Answer №2

It's important to note that the version of angular being used can impact how data is returned by $http. In my experience, the structure returned by $http may vary from what you are seeing in your code.

To retrieve data from an $http request, a potential approach could be:

$http({
    url: '/tasks',
    method: 'get'
}).then(function(result){
    $scope.tasks = result.data;
});

The discrepancy in data structures between $http responses may become evident when examining the contents of result.data.

Consider using console.log(data) to inspect the data being received by the call.

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

Merging JSON Array of Objects from Separate Http Services in Angular 8

I am currently working on a new Angular 8 project where I need to retrieve JSON data from two different services in my component. Both sets of data are arrays of objects. My goal is to merge the objects from these arrays and then post the combined data bac ...

What is the best way to integrate environment-specific configuration options into an AngularJS and Typescript project?

Currently, I am working on a project using AngularJS, Typescript, and VisualStudio. One of the key requirements for this project is to have a configuration file containing constants that control various settings such as REST API URLs and environment names. ...

Tips for confirming date is earlier than current date in Reactjs?

Looking for guidance on how to ensure a date selected by a user is always before the current date when using Material UI in my project. For instance, if it's January 6th, 2021 and the user selects either January 5th or 6th that would be acceptable. Ho ...

Can someone explain to me how this AngularJS factory example functions? I have some uncertainty

As a beginner in AngularJS, I am currently studying it through a tutorial and have some questions regarding the use of the factory in Angular. From what I understand, a factory is a pattern that creates objects on request. In the example provided, we see ...

Ways to match a string against a numeric value

I have a span id with textContent which have their own time(hour/minutes) <div class="here"> <span class="time" >8 min</span> </div> <div class="here"> <span class="time" >22 min&l ...

Why is my website returning a 404 error while attempting to retrieve a JSONObject?

@Override protected JSONArray doInBackground(Long... ids) { id=ids[0]; apiURL="http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=534FA68616FC166C4A9F11CEB01B9929&steamid=76561197976528744&format=json" ...

Guide to implementing dynamic conditional rendering in Vue.js loops (utilizing v-if within v-for)

I am currently working on a table component in a .vue file where I want to display icons based on the direction of the order clicked. For example: <th v-for="(column, index) in columns" :key="index" @click="sort( index )"> <span& ...

Delay the axios get request in the useEffect

Working with React JS, I have implemented a useEffect hook to request data from a database via an Express server when the page renders. However, if the server is down, the app will continue to make thousands of requests until it crashes. Is there a way to ...

How can these lines be drawn in a simple manner?

I have been using the div tag to create a line, but I'm looking for an easier solution. If you have another method in mind, please share it with me. #line{ background-color:black; height:1px; width:50px; margin-top:50px; margin-left:50px; f ...

Getting the parameters of a path from the URL's breadcrumb in Vue.js

Currently utilizing Vue Attempting to include path parameters in breadcrumb URLs for my app's router. Looking to achieve something similar to the following: { path: 'pages/gestion/region/:reg', name: 'gestion-depa', ...

Angular button will be disabled if the form control is empty

Is there a way to deactivate the search button when the text box is empty? I attempted to use the "disabled" attribute on the search button, but it didn't work. Here is my HTML code: <div class="col-md-5 pl-0"> <div class="in ...

What is the best way to determine the quantity of elements received from an ajax request?

Here's the method I am currently using to count the number of li elements returned from an AJAX call: $.post('@Url.Action("actionName", "controller")', function (data) { $('#notificationCounter').html($(data).find('li&a ...

An error of undefined Angular Service/Factory has occurred

I created a factory service called siteCollection: spApp.factory('siteCollection', function(){ return { usersObject : [], getUsers : function (){ $().SPServices({ operation: "GetUserCollectionFromSite", completef ...

Difficulty with obtaining .responsetext in AJAX and PHP

On my real estate website, I have a form for users to 'Add a Property'. Although I will implement form validation later on, here is the current html/js code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

The performance implications of implicit returns in Coffeescript and their effects on side effects

Currently, I am developing a node.js web service using Express.js and Mongoose. Recently, I decided to experiment with CoffeeScript to see if it offers any advantages. However, I have come across something that has left me a bit unsettled and I would appre ...

What methods and applications are available for utilizing the AbortController feature within Next.js?

My search application provides real-time suggestions as users type in the search box. I utilize 'fetch' to retrieve these suggestions from an API with each character input by the user. However, there is a challenge when users quickly complete the ...

Deciphering JSON feedback strings using Objective-C

"[ { \"CinemaName\": \"MaxMovies\", \"CinemaId\": 1, \"Location\": \"Mumbai\" }, { \"CinemaName\": \"SilverScreens\", \"CinemaId\": 2, \"Loca ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

The functionality of AngularJS ng-pattern does not behave as anticipated when used with specific conditions

I have been attempting to use conditions with ng-pattern, but it constantly shows the zip code as invalid. If I remove the condition and just use the pattern, everything works fine. <md-input-container flex="20"> <label>Zip Code ...

Is there potentially a memory leak in this code? If there is, what steps can be taken to eliminate it?

Recently I inherited a project from my senior colleagues that focused on seamless page reloading using AJAX. The code is filled with numerous functions like this one: function iCreateProblems() { //some random code document.getElement ...