Angular - 将HAL转换为JSON

时间:2017-12-09 11:21:56

标签: json angular

以下服务从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
  }
}

2 个答案:

答案 0 :(得分:2)

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,我们必须使用管道(地图)

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

答案 1 :(得分:0)

请尝试以下操作:

// first save the comment
Comment.create(commentProps, function(err, comment) {
    if(err)
    {
      // save the world
    }
    else
    {
        BlogPost.update({ _id: req.param('id') }, { $push: { comments: comment._id } }, function(err, numberAffected, raw) { /*...*/ });
    });