首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有HATEOAS服务器的角4 HttpClient

带有HATEOAS服务器的角4 HttpClient
EN

Stack Overflow用户
提问于 2017-08-01 16:19:09
回答 1查看 3.2K关注 0票数 3

我的Range4应用程序使用Spring服务器,我使用的是HttpClient,我看到它返回对象,而不是像http一样的any。我读到了这个问题:Why does the httpclient in angular 4.3 return Object instead of any?和我明白了。我有许多类似于这样的领域的复杂的json:

代码语言:javascript
复制
{
  "_embedded": {
    "customers": [
      {
        "sid": "c44fdb6f-9b7c-4f75-8d4c-7542f54037b7",
        "createdDate": "2017-08-01T13:06:23Z",
        "lastModifiedDate": "2017-08-01T13:06:23Z",
        "lastModifiedBy": "admin",
        "name": "Customer 1",
        "username": "customer1",
        "address": "Via xxxxx",
        "city": "Adria",
        "landlinePhone": "+39042000000",
        "mobilePhone": null,
        "email": "email@test.it",
        "fax": null,
        "vatNumber": "IT01000020295",
        "taxCode": null,
        "iban": null,
        "swift": null,
        "enableEcommerce": true,
        "balance": 0,
        "enabled": true,
        "new": false,
        "_links": {
          "self": {
            "href": "....:8080/api/v1/customers/1"
          },
          "customer": {
            "href": "....:8080/api/v1/customers/1"
          },
          "movements": {
            "href": "....:8080/api/v1/customers/1/movements"
          },
          "country": {
            "href": "....:8080/api/v1/customers/1/country"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "....:8080/api/v1/customers{?page,size,sort}",
      "templated": true
    },
    "profile": {
      "href": "....:8080/api/v1/profile/customers"
    },
    "search": {
      "href": "....:8080/api/v1/customers/search"
    }
  },
  "page": {
    "size": 20,
    "totalElements": 1,
    "totalPages": 1,
    "number": 0
  }
}

HttpClient不允许执行response.page.totalElements,因为正如我所说的,响应类型是一个对象,而不是any类型。我想知道实现我的目标的最佳方法是什么,我有两个想法:

  • 转换对any的响应。当然,在这种情况下,我可以不需要任何打字机就可以访问字段。
  • 创建几个对象来映射HATEOAS响应:对于每个模型实体,我可能至少需要2-3个接口和一个以上的类。这种方法看起来相当复杂,与第一种解决方案相比,可能会有些过分,而且我总是需要从对象到特定实体模型的转换;这意味着,由于类型错误,我可能会出现运行时异常。

你能给我一些建议和最佳实践,以达到我的目标和遵循的想法角的团队画?

EN

回答 1

Stack Overflow用户

发布于 2017-11-02 15:22:10

我也有同样的问题,我找到了一个可能的解决方案:

代码语言:javascript
复制
// Java: Spring Data REST Repository
@RepositoryRestResource(collectionResourceRel = "result", path = "customers")
public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {
}

// TypeScript model
export interface ListResult<T> {
   _embedded: EmbeddedList<T>;
  _links: any;
  page: any;
}

export interface EmbeddedList<T> {
  results: T[];
}

export class Customer{
  name: String;
  ... bla bla ...
}

// AJAX Call
http.get('/api/customers').subscribe(response => {
  const customers: Customer[] = response._embedded.results;
});

所有存储库都必须有collectionResourceRel="results".

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45442927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档