我有一个 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 发出 get 请求。
用户.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 方法。
用户.组件.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 对象=data
,我可以从中看到我想要的正确信息data._embedded_users
。但它不能映射到 User[] 因为_embedded
不是我的用户模型的属性。我需要先对 Hal+Json 对象做一些事情吗?