TypeScript继承和注入的构造方法参数

时间:2018-07-29 16:11:06

标签: angular typescript angular5

在以下继承方案中,使用Angular 5和TypeScript是否可以不必将MyService作为constructor的{​​{1}}的参数?

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. } } 中的[ts] Expected 1 arguments, but got 0.

重点是我想在MyComponent中加入MyService,以避免在从其继承的类中进行代码重复,例如CAdvanced

1 个答案:

答案 0 :(得分:1)

您可以将可注射服务设置为属性。

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

    constructor() {
    }
}

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

Angular将通过@Inject装饰器将服务注入基类。

或者,您可以将参数设为可选。

这将使错误消失,但是值将为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
    }
}