简体   繁体   中英

Angular: How to pass arguments from derived component class to base class

I am upgrading from Angular 7 to Angular 12.

I have a number of component which all derive from a common base class, where I pass in some constructor arguments.

Base Component

export abstract class PageBase implements OnDestroy{
    constructor(
            moduleName: string,
            protected logger: Logger,    
        ) {
    }

Derived Component

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

When building after the upgrade, I get the following error

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{

From this post , I have added the @Component({template: ''}) , so I now have

@Component({template: ''})
export abstract class PageBase implements OnDestroy{

But now I get a error complaining about the string I pass in from each derived class

    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,
                 ~~~~~~~~~~

If I remove the ngOnDestroy from the base class, I can then remove the @Component({template: ''}) , and it all builds again.

But I was using ngOnDestroy to do common cleanup for all derived classes (eg common rgrx subscriptions)

Any ideas what I need to do here to still be able to have ngOnDestroy in the base class?

Thanks in advance

Because Angular takes over the constructor() function with the injector. You may use an abstract property.:

abstract component PageBase

export abstract class PageBase implements OnDestroy{

abstract moduleName: string;

constructor(protected logger: Logger) {}

ngOnDestroy() {
 console.log(this.moduleName);

}

MyPageComponent

export class MyPageComponent extends PageBase implements OnInit { 

moduleName = 'MyPageComponent';

constructor(logger: Logger,    
   protected actions$: Actions) {

   super(logger); // <-- pass arg to base class
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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