【发布时间】:2019-12-16 09:19:01
【问题描述】:
数据库中有两个实体“人”和“姓名”。这两个实体之间是多对多关系,具有“从”和“到”两个属性。
Person PersonName Name
---------- ------------- -----------
id: number from: number id: number
to: number firstname: string
lastname: string
Spring-Boot 后端将所有人的 json 数组发送到 Angular 前端。
Person 的 Json 对象如下所示:
{
id: 1,
names: [
{
from: 1733,
to: 1735,
name: {
id: 1,
firstname: John,
lastname: Doe
}
}, ...
]
我的 Angular 服务如下所示:
export class PersonService {
constructor(private http: HttpClient) { }
getAll(): Observable<any> {
return this.http.get('//localhost:8080/person')
};
}
我为实体和关系构建类。例如看起来像这样的名称类:
export class Name {
id: number;
firstname: string;
lastname: string;
}
如何将 Json-Array 转换为 Typescript 类的对象? 目标是 getAll() 返回一个 Person[] 类型的 Observable。
将 this.http.get('//localhost:8080/person') 更改为 this.http.get<Person[]>('//localhost:8080/person') 不会返回 Person 数组。
【问题讨论】:
-
你试过使用 JSON.parse 吗?
-
如果您可以更改 API 以返回 Person 对象列表,则最好。数组响应看起来不像一个人,因为它有一个名称数组。
-
如果您的 person 类与返回的 JSON 匹配,那么它就是这样。 TS 类不会为您做任何映射,如果您需要,您可以编写一个映射器..
标签: json angular typescript spring-boot http