【发布时间】:2019-06-03 06:20:18
【问题描述】:
我正在使用最新版本的 Angular (7.x.x)。 我有一个 JSON API,看起来像:
{
"objectA": {
"a": {
"aa": "hello",
"ab": "xyz"
},
"b": null,
"c": {
"ca": null,
"cb": null,
"cc": null,
"cd": "hi",
"ce": null,
"cf": null
}
},
"objectB": {
"a": {
"aa": "hey",
"ab": "abc"
},
"b": null,
"c": {
"ca": null,
"cb": null,
"cc": null,
"cd": null,
"ce": null,
"cf": null
}
}, ...}
我所有的对象都具有相同的结构。现在我想将它们映射到一个打字稿对象。
我的模型看起来像:
export interface MyObject {
name: string;
a: A;
b?: any;
c: C;}
export interface C{
ca?: any;
cb?: any;
cc?: any;
cd?: any;
ce?: any;
cf?: any;}
export interface A {
aa: string;
ab: string;
ac?: string;}
如何将“objectA”等对象的名称放入接口“Object”的变量“name”中。结果我想返回一个对象数组。
我的服务:
getResults(): Observable<MyObject[]> {
return this.http.get<MyObject[]>(this.url, {
headers: this.headers
})
我的组件:
ngOnInit() {
this.getObjects();}
getObjects(): void {
this.service.getResults()
.subscribe(data=> {
this.objects= data;
});}
谁能帮帮我?提前致谢。
【问题讨论】:
-
您可以使用
startsWith('object')来识别每个不同的“条目” -
请给出想要的结果示例
-
JSON 响应是一个数组吗?如何为这样的重复对象创建模型?
标签: json angular typescript mapping