【问题标题】:Angular - convert HAL to JSONAngular - 将 HAL 转换为 JSON
【发布时间】:2017-12-09 11:21:55
【问题描述】:

以下服务从 REST 服务中提取类别对象,该服务以 HAL 格式返回它们。现在我尝试将该响应转换为 JSON。为此,我搜索并尝试了不同的解决方案,例如chariotsolutionsso。有些是基于 '@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 替换为 HttpClient angular.io/guide/http
  • 你没有数组,只有对象。在Array中使用map进行变换
  • @Günther:它不仅是 JSON,而且是 HAL。使用所示代码,我收到以下错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到数组等Iterables。 @Eliseo:我把this.http.get&lt;Category[]&gt;(this.categoriesUrl); 改成了this.http.get(this.categoriesUrl).map(value =&gt; ???;,但是不知道怎么转成数组。
  • HAL 只是 JSON 或 XML stateless.co/hal_specification.html
  • 确实如此。但是,当问这个问题时,我认为需要删除 HAL 的“额外”部分,以便 Angular 可以“使用”它。但是,正如 Eliseo 在下面指出的那样,似乎不再需要使用 httpClient。

标签: json angular hal-json


【解决方案1】:
getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl)
        .map((result:any)=>{
           console.log(result); //<--it's an object
           //result={"_embedded": {"categories": [..]..}
           return result._embedded.categories; //just return "categories"
        });
}

在 Rjxs 6.0 中,我们必须使用 pipe(map)

getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl).pipe(
        map((result:any)=>{
           console.log(result); //<--it's an object
           //result={"_embedded": {"categories": [..]..}
           return result._embedded.categories; //just return "categories"
        }));
}

【讨论】:

  • 这给了我 ERROR in src/app/category.service.ts(29,21): error TS2304: Cannot find name '_embedded' 在编译器中。 Atom 也抱怨同样的消息:ReferenceError: _embedded is not defined
  • 试试 this.http.get(this.categoriesUrl).map((result:any)=>{console.log(result)} 并检查返回的内容。@Rakesh,如果我们使用httpClient,我们不需要解析 JSON
  • 同意你的意见。
  • 我尝试了getCategories(): Observable&lt;Category[]&gt; { return this.http.get(this.categoriesUrl).map((result:any)=&gt;{console‌​.log(result)}); },但无法编译:错误在 src/app/category.service.ts(25,7): error TS2322: Type 'Observable' is不可分配给类型 'Observable'。类型“void”不可分配给类型“Category[]”。 src/app/category.service.ts(25,67):错误 TS2552:找不到名称“控制台”。您指的是“控制台”吗?
  • @Eliseo map() 从 AngularJs 6 开始需要被包裹在 pipe() 中
【解决方案2】:

尝试以下操作:

getCategories(): Observable<Category[]> {
    return this.http.get<Category[]>(this.categoriesUrl).map((response)=>{
        return response;
    })
}

【讨论】:

  • 这让我仍然 找不到“object”类型的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays。
  • 尝试调试您在响应中得到的值,如果是字符串,则使用 JSON.parse 获取类别的集合。
  • 我尝试使用我的问题中的代码并将结果发布在原始问题中。
  • @Mfried,你发布的结果是一个对象。此对象具有以下属性:“_embedded”、“_links”和“page”。属性“_embedded”有一个属性“categories”,即您要查找的数组。这就是我建议您必须返回 result._embedded.categories 的原因。抱歉,我只放了 _embedded.categories。检查代码更正
  • 太棒了!从这里我可以继续我的学习经历。 @Rakesh:也谢谢。这是我的版本:getCategories(): Observable&lt;Array&lt;Category&gt;&gt; { return this.httpClient.get&lt;Array&lt;Category&gt;&gt;(this.categoriesUrl).map((result: any) =&gt; { return result._embedded.categories; }); }
猜你喜欢
  • 2017-07-04
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 2019-05-24
  • 1970-01-01
相关资源
最近更新 更多