带有 HATEOAS REST 服务器的 Angular 4 HttpClient

Ale*_*dro 3 hateoas angular

我的 Angular 4 应用程序使用 Spring Data REST API HATEOAS 服务器,我使用的是 HttpClient,我看到它返回 Object 而不是any像 http。我读到这个问题:为什么 angular 4.3 中的 httpclient 返回 Object 而不是 any? 我明白了。我有很多像这样的字段的复杂 json:

{
  "_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
  }
}
Run Code Online (Sandbox Code Playgroud)

HttpClient 不允许这样做,response.page.totalElements因为就像我说的,响应类型是一个 Object 而不是 type any。我想知道哪种方法是实现我的目标的最佳方式;我有两个想法:

  • 将响应投射到any. 在这种情况下,我当然可以在没有任何类型检查的情况下访问字段。

  • 创建多个对象来映射 HATEOAS 响应:对于每个模型实体,我可能至少需要 2-3 个接口和 1 个类。这种方法看起来很复杂,与第一个解决方案相比可能有点矫枉过正,我总是需要从对象到我的特定实体模型的转换;这意味着由于错误的类型转换,我可能会遇到运行时异常。

你能给我一些建议和最佳实践来实现我的目标并遵循 angular 团队提出的想法吗?

小智 5

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

// 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;
});
Run Code Online (Sandbox Code Playgroud)

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