2016-10-10 29 views
0

我正在使用反射元數據0.1.2。我有一個父類「MyCustom」。reflect-metadata Reflect.getMetadata()方法不返回所提供對象的原型鏈上的元數據

export class MyCustom {} 

我的「Home」組件類擴展了這個「MyCustom」類。

@Component({ 
    selector: 'home', 
    templateUrl: './app/components/home/home.html', 
    styleUrls: ['./app/components/home/home.css'] 
}) 
export class Home extends MyCustom { 
} 

我的目的是讓所有,使用下面的方法調用擴展「MyCustom」類的類的元數據。

let annotations = Reflect.getMetadata('annotations', MyCustom); 

()表示對方法Reflect.getMetadata的意見,

獲得目標 對象或其原​​型鏈上所提供的元數據鍵的元數據值。

但是我什麼也沒得到。如果我添加@Component爲「MyCustom」類像下面,

@Component({ 
    selector: 'hello' 
}) 
export class MyCustom {} 

我得到一個結果是「MyCustom」註釋。

爲什麼我沒有得到子類的註釋?任何幫助,高度讚賞。

回答

1

元數據保存爲Home而不是MyCustom,並且繼承在此處不起作用。

你可能會做的是讓你自己的裝飾器爲父類添加元數據,然後用所需的值調用Component裝飾器。
喜歡的東西:

function MyComponent(props: any) { 
    return (ctor) => { 
     Reflect.defineMetadata('annotations', ctor.prototype.name, ctor.prototype); 
     return Component(props)(ctor); 
    } 
} 

@MyComponent({ 
    selector: 'home', 
    templateUrl: './app/components/home/home.html', 
    styleUrls: ['./app/components/home/home.css'] 
}) 
class Home extends MyCustom {} 

我沒有測試過,以前沒有做過類似的事情,但它也許應該工作。


爲什麼不使用「註冊表」?
有這樣的事情:

const REGISTRY: { [name: string]: MyCustom } = {}; 

然後,對於每一個這樣的組件註冊:

class Home extends MyCustom { 
    ... 
} 

REGISTRY["home"] = Home; 

註冊表和組件沒有要在同一個文件,只要你在需要時導入它。

然後從您的主要組件中可以輕鬆獲得所有這些組件。

+0

感謝您的回覆。我試圖使用它,但迄今爲止沒有運氣。讓我給出我想要做的事情的完整概述。我的主應用程序在開始時並不知道子組件(基本上是標籤)。我正在嘗試使用自定義註釋對子組件進行註釋,並從我的主要組件中掃描它們並添加它們。 –

+0

只有掃描註釋的方法是Reflect.getMetadata(),它需要目標對象。這就是爲什麼我試圖使用超級類作爲「MyCustom」,並讓我的子組件擴展它。 (當時我希望這反映。getMetadata('annotations',MyCustom);也會返回子類的註釋) –