2017-09-18 24 views
3

我正在構建一個應用程序,部分代碼允許開發人員指定他們想要呈現某個部分的組件。我希望用戶知道他們需要實現一個接口,但我不確定如何正確書寫輸入。如何使用類構造函數爲類實例定義接口

export interface ICustomComponent { 
    templateObject: any; 
} 

export class MyComponent implements ICustomComponent { 
} 

export class MyLib { 
    constructor(
     private yourComponent: ICustomComponent 
    ) {} 
} 

new MyLib(MyComponent); <== Fails 

我寫有角的代碼,我不能運行新的運營商,但讓角度來解決,並構建該組件。

Here一個說明我的問題的例子。

如何處理這個問題?

+0

你想在這裏傳遞什麼'new MyLib(...);'?像'new MyLib(new MyComponent());'或者類的引用的實例? –

+0

https://angular.io/guide/dynamic-component-loader#resolving-components這個例子只是爲了說明問題 – tom10271

+0

所以你想通過'MyComponent'到componentFactoryResolver.resolveComponentFactory(MyComponent);'? –

回答

2

由於MyLib需要一個類的構造函數,而不是類的實例,你需要定義一個接口的類的構造函數,並指定其與ICustomComponent接口返回實例:

interface ICustomComponent { 
    templateObject: any; 
} 

interface ICustomComponentConstructor { 
    new (...deps: any[]): ICustomComponent; 
} 

然後你就可以使用它像這樣:

export class MyComponent implements ICustomComponent { 
    templateObject: any; 
} 

export class MyLib { 
    constructor(private yourComponent: ICustomComponentConstructor) { 
    } 
} 

new MyLib(MyComponent); 

您可以閱讀關於類構造函數和實例的接口here

相關問題