【问题标题】:Displaying Spring REST data with AngularJS使用 AngularJS 显示 Spring REST 数据
【发布时间】: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


    【解决方案1】:

    您的控制器并不是真正的 REST 控制器。首先,不要手动创建 JSON - 有数以百万计的工具可以为你做这件事。 Spring 将其中一些开箱即用(faxterxml)。只需返回您的文章集合并让 spring 将其序列化为 json。您的控制器应如下所示:

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

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

    哦,我刚刚意识到您的 AngularJS 代码也是错误的。您正在返回一个带有 articles 属性的 JSON object,但您将整个对象分配给 $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 代码 - 它的代码真的很臭。

    【讨论】:

    • 谢谢,现在可以了。我是这个主题的新手,找不到可用的例子,所以我可能会犯一些大错误
    • @arslanbenzer 我很乐意提供帮助。你可以在 Spring 官方网站 spring.io 上找到很多很棒的例子。他们还托管了很多 github 示例。始终尝试首先在此处找到合适的指南:spring.io/guides(定期更新)。然后,按照他们的指南在他们的官方 github 存储库中找到工作示例:github.com/spring-guides
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 2020-11-20
    • 2018-04-13
    • 2016-02-28
    • 2017-08-16
    • 2016-03-30
    相关资源
    最近更新 更多