【发布时间】:2017-12-09 11:21:55
【问题描述】:
以下服务从 REST 服务中提取类别对象,该服务以 HAL 格式返回它们。现在我尝试将该响应转换为 JSON。为此,我搜索并尝试了不同的解决方案,例如chariotsolutions 或 so。有些是基于 '@angular/http' 的响应,该响应已被弃用且我无法正常工作。
如何进行转换?
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Category } from './category';
@Injectable()
export class CategoryService {
private categoriesUrl = 'http://localhost:8080/account/categories';
constructor(private http: HttpClient) { }
getCategories(): Observable<Category[]> {
return this.http.get<Category[]>(this.categoriesUrl);
}
}
作为 HAL 的响应
{
"_embedded": {
"categories": [
{
"id": 1,
"name": "hardware",
"description": "comprises all computer hardware",
"level": "FIRST",
"_links": {
"self": {
"href": "http://localhost:8080/account/categories/1"
},
"categoryEntity": {
"href": "http://localhost:8080/account/categories/1"
}
}
},
{
"id": 2,
"name": "hardware_notebook",
"description": "all notebooks",
"level": "SECOND",
"_links": {
"self": {
"href": "http://localhost:8080/account/categories/2"
},
"categoryEntity": {
"href": "http://localhost:8080/account/categories/2"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/account/categories{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/account/profile/categories"
}
},
"page": {
"size": 20,
"totalElements": 8,
"totalPages": 1,
"number": 0
}
}
【问题讨论】:
-
响应看起来像有效的 JSON。问题是什么?
Http替换为HttpClientangular.io/guide/http -
你没有数组,只有对象。在Array中使用map进行变换
-
@Günther:它不仅是 JSON,而且是 HAL。使用所示代码,我收到以下错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到数组等Iterables。 @Eliseo:我把
this.http.get<Category[]>(this.categoriesUrl);改成了this.http.get(this.categoriesUrl).map(value => ???;,但是不知道怎么转成数组。 -
HAL 只是 JSON 或 XML stateless.co/hal_specification.html
-
确实如此。但是,当问这个问题时,我认为需要删除 HAL 的“额外”部分,以便 Angular 可以“使用”它。但是,正如 Eliseo 在下面指出的那样,似乎不再需要使用 httpClient。