I am receiving the below JSON which i am trying to map to the objects i have defined
{
"nodes":[
{
"branchId":1,
"branchLevel":1,
"branchOrder":1,
"branchDescription":"BR01",
"leaves":[
{
"clTechForm":"TF01",
"branchId":1,
"leafOrder":1
},
{
"clTechForm":"TF02",
"branchId":1,
"leafOrder":2
}
]
}
]
}
I have the following TypeScript Classes to which i am trying to map the JSON i have received above:
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) {
}
}
I would like to map the received JSON to the following JSON.
{
"nodes":[
{
"id":1,
"name":"BR01",
"children":[
{
"name":"TF01",
"id":1,
},
{
"name":"TF02",
"id":1,
}
]
}
]
}
Here is my HTTP call to the Backend:
getTrees(): Observable<TreeMapper[]> {
return this.http.get('some url').map(
(response: Response) => (response.json())
).catch(
(error: Response) => {
return Observable.throw('Nodes Fetch Failed');
}
);
}
Please help me out in mapping to the Object i have defined above. Any help would be appreciated.
you dont require map
, just do this
in service.ts
getTrees(): Observable<TreeMapper[]> {
return this.http.get('some url');
}
in component.ts
treemappers: TreeMapper[];
getTrees() {
this.service.getTress().subscribe(data => this.treemappers = data);
//write catch code
}
Async Pipe
if you are not doing any processing on data received from http call make use of async
pipe it will do work for you
in service.ts
getTrees(): Observable<TreeMapper[]> {
return this.http.get('some url');
}
in component.ts
treemappers: Observable<TreeMapper[]>;
getTrees() {
this.service.getTress();
//write catch code
}
in component.thml
<table>
//rest of code
<tr *ngFor="let mapper of treemappers | async">
//rest of code
</table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.