从一个 Hal+JSON 对象中解析信息 Angular 2

Parse information from a Hal+JSON object in Angular 2

我有一个 spring-data-rest 存储库,它生成一个 hal+json 对象,我希望我的 Angular 2 前端能够接收和显示该对象。

Hal+Json 对象:

{
  "_embedded" : {
    "users" : [ {
      "name" : "Bob",
      "_links" : {
        "self" : {
          "href" : "http://localhost:4200/api/users/1"
        },
        "user" : {
          "href" : "http://localhost:4200/api/users/1"
        }
      }
    }, {
      "name" : "Joe",
      "_links" : {
        "self" : {
          "href" : "http://localhost:4200/api/users/2"
        },
        "user" : {
          "href" : "http://localhost:4200/api/users/2"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:4200/api/users"
    },
    "profile" : {
      "href" : "http://localhost:4200/api/profile/users"
    },
    "search" : {
      "href" : "http://localhost:4200/api/users/search"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 2,
    "totalPages" : 1,
    "number" : 0
  }
}

我有一项服务可以对此 api 发出获取请求。

user.service.ts:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { User } from './user.model';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class UserService {

  constructor(private http: Http) {
  }

  findAllUsers(): Observable<Array<User>> {
    return this.http.get('/api/users')
      .map((response: Response) => response.json())
      .map((data: Array<User>) => {
        return data;
      });
  }
}

然后我的 users.component 从服务中调用 findAllUsers 方法。

users.component.ts

import { Component, OnInit } from '@angular/core';
import { User } from './user.model';
import { UserService } from './user.service';

@Component({
  selector: 'app-users',
  providers: [UserService],
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
  users: User[];

  constructor(private userService: UserService) {
  }

  ngOnInit(): void {
   this.userService.findAllUsers().subscribe((data: Array<User>) => {
     this.users = data;
   });
  }

}

最后,users.component.html:

<h4>Users:</h4>

<div *ngFor="let user of users">
  {{user}}
</div>

在我看来,我收到一条错误消息:Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.我不确定如何解决这个问题。

如果我在服务返回data之前尝试使用调试器,那么我可以看到我的hal+json object = data,我可以看到正确的信息我想要 data._embedded_users。但这不能映射到 User[],因为 _embedded 不是我的用户模型的 属性。我需要先对 Hal+Json 对象做些什么吗?

Do I need to do something to the Hal+Json object first?

不明显吗?只需提取服务中的数据

findAllUsers(): Observable<Array<User>> {
  return this.http.get('/api/users')
    .map((response: Response) => response.json())
    .map((data: any) => {
      return data._embedded.users as User[];
    });
}

你之前有什么

.map((data: Array<User>) => {
  return data;
});

是不正确的,因为您假设传递给第二个 map 的数据是用户数组,而实际上它是整个 HAL 对象。将其更改为 any 允许你们两个从中提取用户。