繁体   English   中英

Angular:如何将参数从派生组件类传递给基类

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM