2017-09-30 63 views
0

之前我執行「的父母,孩子的」來自同一類派生的幾個對象之間的關係角打字稿:將對象作爲另一個對象的屬性的定義

我的類(模型)如下:

export class Node { 
    public name: string; 
    public isLocked: boolean; 
    public canBeUnlocked: boolean; 
    public parentNodes: Node[]; 
    public childNodes: Node[]; 
} 

在我的部分我聲明瞭該模型得到的幾個對象,但他們的純聲明之前的一些對象是使用對象:

Test.component.ts

import { Component, OnInit } from '@angular/core'; 
import {Node} from '../models/node.model'; 

@Component({ 
    selector: 'app-mage', 
    templateUrl: './test.component.html', 
    styleUrls: ['./test.component.css'] 
}) 
export class TestComponent implements OnInit { 
    NodesList= []; 
    Node1: any; 
    Node2: any; 
    Node3: any; 
    Node4: any; 
    Node5: any; 
    Node6: any; 

    constructor() { 
    this.Node1 = new Node('Node1', false, true , null, [this.Node2]); 
    this.Node2 = new Node('Node2', true, true, [this.Node1], [this.Node3 , this.Node4]); 
    this.Node3 = new Node('Node3', true, false , [this.Node2], [this.Node5]); 
    this.Node4 = new Node('Node4', true, false , [this.Node2], [this.Node6]); 
    this.Node5 = new Node('Node5', true, false , [this.Node3], null); 
    this.Node6 = new Node('Node6', true, false , [this.Node4], null); 
    // The list 
    this.NodesList = [this.Node1, this.Node2, this.Node3 , this.Node4 , this.Node5 , this.Node6]; 
    } 

    ngOnInit() { 
    console.log(this.Node2); 
    console.log(this.NodesList); 
    } 
} 

的概率LEM,與「子節點」

例如節點1節點2是一個子節點,但它的調用console.log(Node1)時得到「未定義」,也許是因爲我」打電話是節點2作爲Node1上的屬性,定義節點2 本身之前。

問題與其他節點發生類似。

任何想法來處理? 建議?

回答

0

它僅僅是未定義的,不可能未定義的對象的的console.log值。解決方案取決於你的目標。

例如,您可以:

public parentNodes?: Node[]; 
    public childNodes?: Node[]; 
} 

這將允許創建無子節點的對象,所以執行console.log將輸出的客體,只是沒有尚未草簽的一些屬性。

或者:

<div> {{ Node2.childNodes?[0] }} </div> 

這將顯示HTML第一childNode如果節點有它。

你也可以在其他一些角度的lifeCycleHook添加缺少的childNodes:

ngOnInit() { 
    this.Node2.childNodes = [this.Node1, this.Node3]; 
} 

ngAfterViewInit() { 
    console.log(this.Node2); 
    console.log(this.NodesList); 
} 
0

你已經發現了問題:它們分配一個值之前,您正在使用的變量。就拿這兩條線:

this.Node4 = new Node('Node4', true, false , [this.Node2], [this.Node6]); 
... 
this.Node6 = new Node('Node6', true, false , [this.Node4], null); 

this.Node4試圖以this.Node6分配一個值之前使用this.Node6。並且您不能交換這些行,因爲this.Node6將在分配值之前使用this.Node4

解決的辦法是分配第一權值給變量,後來確定它們之間的關係,如下所示:

this.Node4 = new Node('Node4', true, false); 
... 
this.Node6 = new Node('Node6', true, false); 
.. 
this.Node4.parentNodes = [this.Node2]; 
this.Node4.childNodes = [this.Node6]; 
... 
this.Node6.parentNodes = [this.Node4]; 
相關問題