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?