【发布时间】:2017-09-25 16:45:38
【问题描述】:
我想开发一个带有 Java Spring 后端和 AngularJS 前端的博客系统。 我写下了 API,但我不知道如何使用 AngularJS 来使用它们。这是我的 API 代码。
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;
}
....
}}
对于 getarticles api http://localhost:8080/getarticles
我收到此回复
{ "articles":{"id":"1", "text":"bu bir article", "author":"ali",
"likes":"0"},{"id":"2", "text":"bu bir article2", "author":"veli",
"likes":"0"}}
我写了一些简单的 AngularJS 代码
'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'
});
});
使用 home.html 文件
<!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>
html文件和app.js在src/main/java/static
我无法从 localhost 获取文章,home.html 只是显示
this is a test
a line
a line2
如何从 Spring REST 获取数据并使用 angularJS 代码显示?
【问题讨论】:
标签: java angularjs spring spring-mvc