Ben
Ben

Reputation: 16659

TypeScript Inheritance and Injected Constructor Arguments

Using Angular 5 and TypeScript, in the following inheritance scenario, is it possible to not have to include MyService as an argument to the constructor of MyComponent?

export class CBasic {
    // properties and methods
}

export class CAdvanced extends CBasic {

    // constructor
    constructor(
        public myService: MyService
    ) {
        // call constructor of super-class (required)
        super();
    }

    // more properties and methods
}

export class MyComponent extends CAdvanced {

    // constructor
    constructor() {
        // call constructor of super-class (required)
        super(); // Error: [ts] Expected 1 arguments, but got 0.
    }
}

The error I am getting is [ts] Expected 1 arguments, but got 0. in MyComponent.

The point is I want to include MyService in CAdvanced to avoid code-duplication in classes that inherit from it, e.g. MyComponent.

Upvotes: 1

Views: 3306

Answers (1)

Reactgular
Reactgular

Reputation: 54771

You can make the injectable service a property.

export class CAdvanced {
    @Inject(MyService)
    public myService: MyService;

    constructor() {
    }
}

export class MyComponent extends CAdvanced {
    constructor() {
         super(); // no more error
    }
}

Angular will inject the service to the base class via the @Inject decorator.

Alternatively, you can make the parameter optional.

This will silence the error, but the value will be undefined.

export class CAdvanced {
    constructor(public myService?: MyService) {
        console.log(this.myService);
        // above will print undefined
    }
}

export class MyComponent extends CAdvanced {
    constructor() {
         super(); // no more error
    }
}

Upvotes: 4

Related Questions