Angular 4使用HATEOAS REST服务器的HttpClient

3
我的 Angular 4 应用程序使用 HttpClient 消费 Spring Data REST API HATEOAS 服务器。我看到它返回 Object,而不是像 Http 那样返回 any。 我读了这个问题:为什么 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
  }
}

HttpClient不允许执行 response.page.totalElements,因为响应类型是Object而不是any类型。我想知道实现我的目标的最佳方法是什么;我有两个想法:
  • 将响应强制转换为any类型。在这种情况下,我可以访问字段而不进行任何类型检查。

  • 创建多个对象来映射HATEOAS响应:可能至少需要2-3个接口和每个模型实体的1个类。这种方法似乎相当复杂,与第一个解决方案相比可能过于繁琐,并且我始终需要将对象转换为特定的实体模型;这意味着我可能会因错误的类型转换而导致运行时异常。

您能给我一些建议和最佳实践,以达到我的目标并遵循angular团队的想法吗?


你尝试过response['page'].totalElements吗? - Mackelito
1个回答

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;
});

所有仓库必须具有collectionResourceRel="results"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接