[英]Angular 2+ extend Component by two other components
假設我們有一個包含很多列表的應用程序,因此有一些基本組件
export class SimpleListComponent { ... }
export class ExtendedListComponent extends SimpleListComponent { ... }
...我們可以輕松擴展。 它們具有列表的所有基本功能(例如切換頁面,計數結果等)。 我們將這兩個基本組件用於兩個不同的英雄列表:
export class HeroSimpleListComponent extends SimpleListComponent { ... }
export class HeroExtendedListComponent extends ExtendedListComponent { ... }
不幸的是,我們仍然必須重復很多代碼,因為HeroSlimListComponent
和HeroExtendedListComponent
共享許多功能(例如加載英雄,通往英雄的路線等)。
我的第一次嘗試是通過我們需要擴展的課程
export class ExtendedListComponent<T = SimpleListComponent> extends T { ... }
但這不起作用。 另外,我發現這篇文章指出,打字稿內不可能多重繼承。 仍然有一種感覺,我在這里缺少一些基本的角度分量連接解決方案。
在此先感謝您的幫助!
沒錯,多重繼承是不可用的(不幸的是,因為它太酷了)。
可能性1看來,您的常用操作似乎可以存在於簡單列表組件內部,並且可以在構造函數中提供擴展組件(如路徑)所需的屬性。 當您調用super()時,可以向下傳遞config選項。
export class SimpleListComponent {
constructor(
routePath: string,
) {}
}
// extending component
export class HeroSlimListComponent extends SimpleListComponent {
constructor() {
super('<my-route-path>');
}
}
可能性2可能值得檢查mixin ! 我還沒有玩過這些游戲,所以也許有一些經驗的人可以參與其中? 他們似乎並不能完全解決問題,因為您仍然必須實現接口,但是對於父組件來說,這可能是一組很好的通用功能。
可能性3 (可能是我的個人最愛)將通用列表和擴展列表組件保留為接受輸入,提供輸出但不擴展它們的組件。 而是在html中使用它們。 例如,可以傳遞導航路徑,並可以在父級組件處提供數據服務,並將其注入樹中的子組件中。 要配置列表項,您可以傳入模板引用(請參見材料表示例 )。 這只是一個粗糙的示例,需要進行優化,但是在這里您可以進行以下操作:
// simple list component
// selector = simple-list
constructor(simpleListService: SimpleListService) {}
// hero simple list component
@Component({
....
providers: [
{ provide: SimpleListService, useClass: HeroSimpleListService },
],
})
// html
<simple-list [navPath]='heroNavPath' <...other templates / props>>
需要記住的是,您擴展的類中的每一段代碼都作為每個擴展組件中的重復代碼再次添加到了最終版本中(檢查prod版本的輸出,這很有趣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.