我收到以下JSON,我试图映射到我定义的对象
{
"nodes":[
{
"branchId":1,
"branchLevel":1,
"branchOrder":1,
"branchDescription":"BR01",
"leaves":[
{
"clTechForm":"TF01",
"branchId":1,
"leafOrder":1
},
{
"clTechForm":"TF02",
"branchId":1,
"leafOrder":2
}
]
}
]
}
我有以下TypeScript类,我试图映射我上面收到的JSON:
export class TreeMapper{
constructor(public nodes: BranchMapper[]) {
}
}
export class BranchMapper{
constructor(public id: number, public name: string, public children: TechnicalFormMapper[] ) {
}
}
export class TechnicalFormMapper{
constructor(public id: number, public name: string) {
}
}
我想将收到的JSON映射到以下JSON。
{
"nodes":[
{
"id":1,
"name":"BR01",
"children":[
{
"name":"TF01",
"id":1,
},
{
"name":"TF02",
"id":1,
}
]
}
]
}
这是我对后端的HTTP调用:
getTrees(): Observable<TreeMapper[]> {
return this.http.get('some url').map(
(response: Response) => (response.json())
).catch(
(error: Response) => {
return Observable.throw('Nodes Fetch Failed');
}
);
}
请帮我映射到我上面定义的Object。 任何帮助将不胜感激。
答案 0 :(得分:1)
你不需要map
,只需这样做
in service.ts
getTrees(): Observable<TreeMapper[]> {
return this.http.get('some url');
}
在component.ts
中treemappers: TreeMapper[];
getTrees() {
this.service.getTress().subscribe(data => this.treemappers = data);
//write catch code
}
异步管道
如果您没有对从http呼叫接收的数据进行任何处理,请使用async
管道,它将为您工作
in service.ts
getTrees(): Observable<TreeMapper[]> {
return this.http.get('some url');
}
在component.ts
中treemappers: Observable<TreeMapper[]>;
getTrees() {
this.service.getTress();
//write catch code
}
在component.thml
中<table>
//rest of code
<tr *ngFor="let mapper of treemappers | async">
//rest of code
</table>