java - 使用 AngularJS 显示 Spring REST 数据

标签 java angularjs spring spring-mvc

我想开发一个使用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

我无法从本地主机获取文章,home.html 仅显示

this is a test

a line

a line2

如何从 Spring REST 获取数据并使用 angularJS 代码显示它?

最佳答案

您的 Controller 并不是真正的 REST Controller 。首先,不要手动创建 JSON - 有数百万种工具可以为您执行此操作。 Spring 结合了其中一些开箱即用的(faxterxml)。只需返回您的文章集合并让 spring 将其序列化为 json 即可。您的 Controller 应如下所示:

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

您也不需要 Model 属性。它在创建经典的类似 MVC 的 Controller 时使用,该 Controller 返回例如JSP页面作为模板由服务器处理。

哦,我刚刚意识到你的 AngularJS 代码也是错误的。您正在返回一个带有 articles 属性的 JSON 对象,但您正在将整个对象分配到 $scope.articles 中。因此,ng-repeat无法迭代它。如果您确实想返回内部包含集合的对象,则需要将 $http.get 调用更改为:

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

如果您仅更改 AngularJS 代码,那么您的示例将无需更改 Spring 代码即可运行。但是,我强烈建议您也更改 Spring 代码 - 它的代码真的很臭。

关于java - 使用 AngularJS 显示 Spring REST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43665398/

相关文章:

javascript - 发送发布请求并收到错误 "undefined is not a function"

Spring:spring-data-mongodb 或 spring-boot-starter-data-mongodb

java - 无法使用 iText 显示 unicode 0x0332

java - Gradle build - 添加模块路径

javascript - 过滤AngularJS返回多个元素

angularjs - 使用 angularjs 的嵌套选项卡

java - 来自 Spring 还是 JNDI 的 TransactionManager? (JBOSS + Spring 3 + Hibernate 4 + JTA)

java - 如何在tomcat中部署的不同Web应用程序中访问公共(public)jar中加载的bean

java - JPA CriteryQuery 内连接 - IllegalStateException

java - jMonkeyEngine - 像在第一人称游戏中一样用鼠标旋转