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

Protractor - Issue with clicking on hidden element with "ng-click" attribute

I'm facing an issue with a specific element that I am unable to click using Protractor. Everything was working fine until a few days ago. Technical information: Chrome version: 47.0.2526.106 Protractor version: 2.0 Selenium version: 2.44 CSS &l ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Issues with Angular JS page loading when utilizing session and local storage in Google Chrome

I'm currently learning about AngularJS and I stumbled upon this helpful tutorial http://embed.plnkr.co/dd8Nk9PDFotCQu4yrnDg/ for building a simple SPA page. Everything was working smoothly in Firefox and IE, except when it came to using Local and Sess ...

The table value is only updated once with the onclick event, but the updated value is not displayed when the event is clicked again

I am facing an issue with updating names in a table through a modal edit form. The first name update works perfectly, but the second update does not reflect in the table. I want every change made in the modal edit form to be instantly displayed in the tabl ...

What is the reason that the <script> tag cannot be directly inserted into the .html() method?

As I continue to learn front-end development, I've created my own version of JS Bin. When the 'run' button is clicked, a statement is executed to showcase the HTML, CSS, and JavaScript in an iframe (the output window): ("iframe").contents() ...

Retrieve Browser Screen Width and Height using MVC3 Razor in the View

I am facing a challenge on my website where I need to generate a Bitmap dynamically and ensure it is rendered according to the width and height of the browser so that there are no overflow issues on the page. Although I have successfully created an image ...

Having trouble getting the .toggle() function with classList to work on one element, despite working fine on others

I've been struggling to apply a class to an HTML element when I click on another element of the page. Despite numerous attempts, it just doesn't seem to work for me. Let's take a look at my code: HTML Code: <div class="container&qu ...

In search of a fresh and modern Facebook node template

I've been on the hunt across the internet for a quality node.js Facebook template, but all I seem to stumble upon is this https://github.com/heroku/facebook-template-nodejs. It's okay, but it's built using express 2.4.6 and node 0.6.x. I wan ...

Issue encountered with Powershell: Error in parsing JSON resulting in a NotSpecified error

Snippet for Parsing File: $myJson = Get-Content cleantest_file.json -Raw | ConvertFrom-Json Error Encountered during JSON Parsing Attempt: $myJson = Get-Content cleantest_file.json -Raw | ConvertFrom-Json + ~~~ ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Utilizing HTML's multiple input type color feature to save selected colors directly to the database

I am currently using the input type color to select colors for customizing my site. I save the selected color to a database and then retrieve it to apply it to different areas of the site. This works well for a single input type color, but now I have mul ...

Angular dynamic calculations for min and max values result in an unusual user interface

I am encountering an issue with a datetime-local input field that has max and min attributes. <input type="datetime-local" ng-model="model.date" min="{{min}}" max="{{max}}"> These attributes are dynamically set based on the date from another input ...

Saving the output of an AngularJS expression in an input field

Looking at the calculations below, I am currently evaluating an expression, {{ annualIncome * 4.5 }}, in one input and then re-evaluating the same expression in another input. Instead of saving the result and transferring it to the other input, I am repeat ...

Ways to conceal an item by considering the size of a different element

I have a question about displaying content within a div element. I want to show a "show more" button only if the content inside the div exceeds a max height of 530px. Otherwise, the button should remain hidden. Here is the code snippet I'm using: Ja ...

Exploring the location where an XMLHttpRequest/Ajax link is executed

I am relatively new to the world of Ajax/XMLHttpRequest and I am currently trying to wrap my head around its functionality. My current project involves developing an inventory program that essentially allows users to add tools to a digital box. On the mai ...

When making an Ajax request to another website, the response received is in HTML format instead of

I am attempting to retrieve an array by making an AJAX GET request to a URL. Below is my controller code, which is hosted locally at localhost:3000 def merchant_ids merchants = Merchant.where(id: params[:id]).pluck(:merchant_name, :id, :merchant_city, ...

I often struggle with creating social media buttons using Material UI

Unfortunately, the code provided is not rendering social media icons or buttons as expected. In the initial lines, material UI icons/buttons were imported from the React Material UI library (IconButton / AlarmIcon). import './App.css'; impor ...

In Node.js Express, the download window won't pop up unless the entire file has been sent in the header response

I have been using Express to develop an API that allows users to download PDF files. The download process is functioning correctly, but I am facing an issue where the download window, which prompts me to select a destination folder for the download, only a ...

We have encountered an issue with the syntax in the code: ajaxsample/update_agenda. It seems to be an unrecognized expression according to

Here's the code for updating my controller: public function update_agenda() { $id= $this->input->post('did'); $this->load->model('agenda_model'); $data = array ( ...

Switch Background Image - The image failed to display

Here is the code snippet I am currently working with. It involves displaying a background-image when clicking on a link with the class 'home-link', and not showing an image if the link does not have this class. The issue at hand: The problem ari ...