rocksparrow
rocksparrow

Reputation: 185

How to fetch data from Spark and display using Angular

As a beginner in Spark framework and AngularJS I was trying to build a simple REST application. However I apparently can’t retrieve data from the server and display using Angular.

I started with simple task:

@Data
public class Todo {

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

In order to display the todo in the browser I send a JSON object as a response to get request.

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 part looks 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 the index.html :

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

After running Spark and entering http://localhost:4567/tasks in the browser,it shows only JSON representation:

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

What am I doing wrong?

Upvotes: 0

Views: 2809

Answers (2)

jamesmpw
jamesmpw

Reputation: 525

I'm not sure what version of angular you are using but in the version I use $http returns a different data structure than the one you show.

So to get the data from an $http request I would do something like,

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

The result.data is where the data structure on $http returns differ from what I see in your code.

Try console.log(data) to get a look at what the call is getting back.

Upvotes: 0

abiwer
abiwer

Reputation: 121

In your Spark code you are creating a '/tasks' endpoint, which you are attempting to hit with your angular code. When you try to run this in the browser, you are just hitting your '/tasks' api endpoint which is returning the expected response. You need to create another endpoint in Spark which will serve up the appropriate HTML and JavaScript code.

Upvotes: 1

Related Questions