簡體   English   中英

如何將嵌套JSON樹的所有節點轉換為angular 2 Typescript中的類的實例?

[英]How to cast all nodes of a nested JSON tree to instances of a class in angular 2 Typescript?

我有一個名為Leaf的類,我想制作Leaf的json響應實例的所有節點。 json響應如下所示:

JSON回應

{
    "name":"animal",
    "state":false,
    "children":[
        {
            "name":"cats",
            "state":false,
            "children":[
                {
                    "name":"tiger",
                    "state":false,
                },
                {
                    "name":"puma",
                    "state":false,
                    "children":[
                        {
                            "name":"babyPuma",
                            "state":true
                        }
                    ]
                }
            ]
        },
        {
            "name":"dogs",
            "state":false,
            "children":[
                {
                    "name":"pitbull",
                    "state":true
                },
                {
                    "name":"german",
                    "state":false,
                    "children":[
                        {
                            "name":"shepherd",
                            "state":true
                        }
                    ]
                }
            ]
        }
    ]
}

我正在使用可觀察到的響應,並學會了鑄造第一個節點:

http.service.ts片段

getTreeData(): Observable<Leaf>{  
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:8000/',{ headers: headers ...})
        .map(res =>new Leaf(res.json()));//maybe I could do something here?
}

這是我的Leaf類,以防萬一:

Leaf.ts

export class Leaf{
    name: string;
    state: string;
    treeData: Array<Leaf>;


    constructor(input:any){
        this.name = input.name;
        this.state = input.state;
        this.treeData = input.children;
    }

    toggleState() {
        if (this.state=='active'){
            this.state = 'inactive';
        }
        else {
            this.state = 'active'
        }
    }
}

我的最終目標是獲取json樹並以文件夾樹格式表示它們。 有沒有一種方法可以使用map()遍歷所有節點或map()和某種遍歷器的組合?

我首先要為json數據創建一個接口:

interface LeafJson {
    name: string;
    state: string;
    children?: LeafJson[];
}

然后使用Array.map創建子代:

export class Leaf {
    name: string;
    state: string;
    treeData: Array<Leaf>;

    constructor(input: LeafJson){
        this.name = input.name;
        this.state = input.state;
        this.treeData = input.children ? input.children.map(item => new Leaf(item)) : [];
    }

    toggleState() {
        if (this.state=='active'){
            this.state = 'inactive';
        } else {
            this.state = 'active'
        }
    }
}

操場上的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM