【问题标题】:How to get my resource data from a HAL response?如何从 HAL 响应中获取我的资源数据?
【发布时间】:2019-02-04 02:01:39
【问题描述】:

我正在使用 Spring Boot 2 构建一个 API,而 Angular 6 客户端必须处理诸如此类的响应:

{
  "_embedded" : {
    "userResourceList" : [ {
      "firstname" : "Stephane",
      "lastname" : "Toto",
      "email" : "toto@yahoo.se",
      "confirmedEmail" : false,
      "password" : "bWl0dGlwcm92ZW5jZUB5YWhvby5zZTptaWduZXRjNWRlMDJkZS1iMzIwLTQ4Y2YtOGYyMS0wMmFkZTQ=",
      "userRoles" : [ {
        "role" : "ROLE_ADMIN",
        "id" : 1
      } ],
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/api/users/1"
        },
        "roles" : {
          "href" : "http://localhost:8080/api/users/1/roles"
        }
      },
      "id" : 1
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/users"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

所有 REST 资源端点都会重新运行此类 HALified 响应。

我想知道如何处理这些。如果有这样的库可以简化实际负载的解析和提取。

我听说过 RestAngular 库,但我不太确定它是否是我想要的。

也许一些侵入性较小的东西仅有助于解析,例如:

const user: User = hal2Json.parse<User>(response);

更新:我没有找到任何这样的库,所以我求助于这个实现:

public getSome(searchTerm: string, sortFieldName: string, sortDirection: string, currentPage: number, limit: number): Observable<any> {
  let httpParams = new HttpParams()
  .set('page', currentPage.toString())
  .set('size', limit.toString());
  if (searchTerm) {
    httpParams = httpParams.append('searchTerm', searchTerm);
  }
  if (sortFieldName && sortDirection) {
    httpParams = httpParams.append('sort', sortFieldName + ',' + sortDirection);
  }
  return this.httpService.get(this.usersUrl, httpParams);
}

export class UsersApi extends PaginationApi {

  constructor(users: User[], currentPageNumber: number, elementsPerPage: number, totalElements: number, totalPages: number) {
      super(currentPageNumber, elementsPerPage, totalElements, totalPages);
      this.users = users;
  }

  users: User[];

}

getUsers(searchTerm: string, sortFieldName: string, sortDirection: string, currentPageNumber: number): Observable<UsersApi> {
  return this.userService.getSome(searchTerm, sortFieldName, sortDirection, currentPageNumber, this.elementsPerPage)
    .pipe(
      map(response => {
        return new UsersApi(
          response._embedded.userResourceList as User[],
          this.paginationService.correctPageNumberMispatch(response.page.number),
          response.page.size,
          response.page.totalElements,
          response.page.totalPages
        );
      })
    );
}

【问题讨论】:

    标签: angular spring-boot spring-hateoas


    【解决方案1】:

    定义一个接口来包装 HAL 响应。这就是我为图书服务所做的:

    // book.service.ts
    import { Injectable } from '@angular/core';
    import { Book } from '../book';
    import { Observable, map } from 'rxjs';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable({
        providedIn: 'root'
    })
    export class BookService {
    
        private booksUrl = 'http://localhost:8080/books';
    
        constructor(private http: HttpClient) { }
    
        getBooks(): Observable<Book[]> {
            return this.http.get<GetBooksResponse>(this.booksUrl).pipe(
                map(response => response._embedded.bookList)
            );
        }
    }
    
    interface GetBooksResponse {
        _embedded: {
            bookList: Book[];
            _links: {self: {href: string}};
        };
    }
    

    HAL 回复:

    归功于这篇文章:https://medium.com/@tbrouwer/spring-boot-backend-for-angular-tour-of-heroes-106dc33a739b

    【讨论】:

    • 为提供的链接+1,这对于解决从0到功能齐全的后端/前端过程中的问题非常有帮助
    【解决方案2】:

    你可以试试 halfred npm 模块。似乎做你想做的事:

    https://www.npmjs.com/package/halfred

    npm install halfred --save
    

    然后导入它:

    import * as 'halfred' from 'halfred' // something like this should work
    

    然后使用它:

    const resource = halfred.parse(object)
    

    【讨论】:

    • 看起来这个包已经3年没有更新了。我怀疑它与 Angular 应用程序一起使用。
    猜你喜欢
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2021-11-15
    相关资源
    最近更新 更多