[英]Angular: How to pass arguments from derived component class to base class
我正在從 Angular 7 升級到 Angular 12。
我有許多組件都派生自一個公共基類,我在其中傳遞了一些構造函數參數。
基礎組件
export abstract class PageBase implements OnDestroy{
constructor(
moduleName: string,
protected logger: Logger,
) {
}
派生組件
const moduleName = 'MyPageComponent';
@Component({
selector: 'app-my-page',
templateUrl: './mypage.component.html',
styleUrls: ['./mypage.component.scss']
})
export class MyPageComponent extends PageBase implements OnInit {
constructor(
logger: Logger,
protected actions$: Actions,
) {
super(moduleName, logger); // <-- pass arg to base class
升級后構建時,出現以下錯誤
Error: src/app/shared/page-base.ts:12:23 - error NG2007: Class is using Angular features but is not decorated. Please add an explicit Angular decorator.
12 export abstract class PageBase implements OnDestroy{
在這篇文章中,我添加了@Component({template: ''})
,所以我現在有了
@Component({template: ''})
export abstract class PageBase implements OnDestroy{
但是現在我收到一個錯誤,抱怨我從每個派生類傳入的字符串
Error: src/app/shared/page-base.ts:24:5 - error NG2003: No suitable injection token for parameter 'moduleName' of class 'PageBase'.
Consider using the @Inject decorator to specify an injection token.
24 moduleName: string,
~~~~~~~~~~
如果我從基類中刪除ngOnDestroy
,然后我可以刪除@Component({template: ''})
,它會再次構建。
但是我正在使用ngOnDestroy
對所有派生類(例如常見的 rgrx 訂閱)進行常見清理
有什么想法我需要在這里做什么才能仍然能夠在基類中使用ngOnDestroy
嗎?
提前致謝
因為 Angular 用注入器接管了 constructor() 函數。 您可以使用抽象屬性。:
抽象組件 PageBase
export abstract class PageBase implements OnDestroy{
abstract moduleName: string;
constructor(protected logger: Logger) {}
ngOnDestroy() {
console.log(this.moduleName);
}
我的頁面組件
export class MyPageComponent extends PageBase implements OnInit {
moduleName = 'MyPageComponent';
constructor(logger: Logger,
protected actions$: Actions) {
super(logger); // <-- pass arg to base class
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.