2

I want to develop a blog system with Java Spring back-end and AngularJS front-end. I wrote down the API's but I don't know how to consume them with AngularJS. Here is my code for API's.

package app.com.example;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
.....
....
import app.com.example.UserRepository;
import app.com.example.CommentRepository;
import app.model.Article;
import app.model.Comment;
import app.model.User;

@RestController
public class UserApi {
    @Autowired
    UserRepository repository;
    @Autowired
    ArticleRepository articleRepository;
    @Autowired
    CommentRepository commentRepository;
....
....
@RequestMapping(value="/getarticles")
    public String getarticles(Model model) {
        String response = "{ \"articles\":";
        Iterator <Article> iterator =articleRepository.findAll().iterator();
        while (iterator.hasNext()){
            Article article=iterator.next();
            String s=article.toString();
            response=response+s;
            System.out.println(s+" naber "+response);
            if(iterator.hasNext())
                response=response.concat(",");
        }

        response=response.concat("}");
        model.addAttribute("articles",response);
        return response;
    }
....
}}

And for getarticles api http://localhost:8080/getarticles

I get this response

 { "articles":{"id":"1", "text":"bu bir article", "author":"ali", 
 "likes":"0"},{"id":"2", "text":"bu bir article2", "author":"veli", 
 "likes":"0"}}

I wrote some simple AngularJS code

'use strict';

var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope, $http) {
    $scope.test='this is a test';
    $http.get("http://localhost:8080/getarticles")
    .then(function(response) {
        $scope.articles = response.data;
    },
    function(errResponse){
            console.error('Error while fetching Users');
            deferred.reject(errResponse);
            $scope.error='error getting'
    });
});

With the home.html file

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8">
    <title>Google Phone Gallery</title>
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
    <script src="angular-resource.min.js"></script>
 </head>

<body ng-controller="myCtrl"> 

<h1>{{naber}}</h1>
<h1>a line</h1>
<h1>{{articles}}</h1>
<h1>a line2</h1>
<div ng-repeat="article in articles">{{article.text}} {{article.author}}</div>

</body>
</html>

the html file and app.js are in src/main/java/static

I cannot get articles from localhost, home.html just shows

this is a test

a line

a line2

How can I get data from Spring REST and display it with angularJS code?

1 Answer 1

3

Your controller is not really a REST controller. First of all, do not create your JSON manually - there are million tools that will do this for you. Spring incorporates some of them out of the box (faxterxml). Simply return your articles collection and let spring serialize it into json. Your controller should look like this:

@RequestMapping(value="/getarticles")
public List<Article> getarticles() {
    return articleRepository.findall();
}

You also don't need Model attribute. It's used when creating classic MVC-like controllers which return e.g. JSP page as a template processed by server.

Oh, I've just realized your AngularJS code is wrong as well. You are returning a JSON object with articles property, but you are assigning entire object into $scope.articles. Therefore, ng-repeat cannot iterate it. If you really want to return object with collections inside, you need to change your $http.get invocation to:

$http.get("http://localhost:8080/getarticles")
.then(function(response) {
    // response.data return objects with articles property
    $scope.articles = response.data.articles;
}

If you change only your AngularJS code, then your example will work without changing your Spring code. However, I strongly advice you to change your Spring code as well - its code is really smelly.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, now it worked. I am new at this topic and I couldn't find usable examples, so I can make some big mistakes
@arslanbenzer I'm happy to help. You can find a lot of great examples at official Spring website - spring.io. They're also hosting a lot of github examples. Always try to first find an appropriate guide here: spring.io/guides (it's updated regularly). Then, follow their guides to find working examples at their official github repository: github.com/spring-guides.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.