1

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).

What do I need to do here to still be able to have ngOnDestroy in the base class?

halfer
  • 19,824
  • 17
  • 99
  • 186
peterc
  • 6,921
  • 9
  • 65
  • 131

1 Answers1

1

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
}
Hao pham van
  • 75
  • 1
  • 2
  • 12