【问题标题】:How Angular handle data from Spring JPA Data with RESTAngular 如何使用 REST 处理来自 Spring JPA Data 的数据
【发布时间】:2019-07-14 03:47:07
【问题描述】:

我按照spring官方链接用jpa搭建了一个rest server。这适用于浏览器或 chrome postman 扩展。

https://spring.io/guides/gs/accessing-data-rest/

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

并希望使用 Angular 来显示和处理数据。这是基于 Angular 官方英雄示例。

但我无法处理来自 Spring JPA 休息服务器的响应。 因为格式是 HAL - 超文本应用语言。 看起来像:

        {

      "_embedded" : {

        "persons" : [ {

          "firstName" : "name1",

          "lastName" : "name2",

          "_links" : {

            "self" : {

              "href" : "http://localhost:8080/persons/1"

            },

            "person" : {

              "href" : "http://localhost:8080/persons/1"

            }

          }

        }, 

.......

persons 数组中没有 ID。

如何使用 Angular 处理这种格式? 我应该自己编写javascript代码吗? 如果是这样,如何从 Angular httpclient 的结果中获取原始 JSON 数据?

我尝试编写 spring 控制器来为 Angular 返回正常的 JSON,这很有效。 但是这样我就失去了 Spring JPA Repository 的好处,例如 PagingAndSortingRepository、CrudRepository 和 JpaRepository。

我想保留纯弹簧和角度特征,只需更改角度服务即可获取数据。

【问题讨论】:

    标签: json angular spring rest spring-data-jpa


    【解决方案1】:

    我想我可能没有说清楚这个问题。所以我又研究了这个问题。 原始的spring jpa rest示例给出的结果如下

    在Person类ID的getter和setter之后,添加接口RepositoryRestConfigurer的实现

    //@Configuration
    public class ExposeAllRepositoryRestConfiguration implements RepositoryRestConfigurer {
    
        @Override
        public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
            // TODO Auto-generated method stub
    //      RepositoryRestConfigurer.super.configureRepositoryRestConfiguration(config);
            config.exposeIdsFor(Person.class);
        }
    }
    

    (有一些方法可以添加所有模型类)

    我明白了

    用你的方法我能得到正确的数据吗

    【讨论】:

      【解决方案2】:

      定义一个包装类:

      export class PersonsWrapper{
          _embedded: { person: Person[]};
      }
      

      然后将其用于调用 Spring REST 服务器:

      httpClient.get<PersonsWrapper>(url).pipe(
          map(w => w._embedded.persons)
        ).subscribe(persons => ...);
      

      【讨论】:

      • 它只能部分工作。 “身份证”不见了。这意味着 Person 类不完整。
      • ID 哪里不见了?您可以像从服务器收到的任何内容一样定义 Person 类。如果服务器不发送ID,那么它是在服务器端的实体中配置的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 2013-08-26
      • 2016-01-01
      • 1970-01-01
      • 2021-09-06
      • 2017-11-28
      • 2014-02-04
      相关资源
      最近更新 更多