Excessstone
Excessstone

Reputation: 59

How Angular handle data from Spring JPA Data with REST

I follow the spring official links build a rest server with jpa. This works fine with browser oder chrome postman extension.

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>

And want use Angular to show and handle data. That is based on angular official hero example.

But I can't handle response from Spring JPA rest server. Because the format is HAL - Hypertext Application Language. That looks like :

        {

      "_embedded" : {

        "persons" : [ {

          "firstName" : "name1",

          "lastName" : "name2",

          "_links" : {

            "self" : {

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

            },

            "person" : {

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

            }

          }

        }, 

.......

There is no ID in persons array.

How can I handle this format with angular? Should I write javascript code by my self? If so, how to get the original JSON data from the result of angular httpclient?

I tried write spring controller to return normal JSON for Angular and that works. But in this way I lost the benefit of Spring JPA Repository such as PagingAndSortingRepository, CrudRepository and JpaRepository.

I want keep pure spring and angular features and just change angular service to get the data.

Upvotes: 0

Views: 1109

Answers (2)

Excessstone
Excessstone

Reputation: 59

I think I may talk about this problem not clearly. So I study this problem again. the original spring jpa rest example gives the result like enter image description here

after getter and setter of ID for Person class and add implement of interface 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);
    }
}

(there are some method can add all model classes)

i get this

enter image description here

with your method can I get the correct data

Upvotes: 2

Normunds Kalnberzins
Normunds Kalnberzins

Reputation: 1245

define a wrapper class:

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

then use it for calls to Spring REST server:

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

Upvotes: 1

Related Questions