简体   繁体   中英

Angular 2 DI in base Component

Let's say I have a Base Component -

export class BaseComponent {

    public constructor(public myService: MyService) {

    }

}

And a Derived Component -

export class DerivedComponent extends BaseComponent {

    public constructor(public myService: MyService) {
        super(myService);
    }

}

But I only really need the myService dependency in BaseComponent. Is there any way to avoid having to add the extra constructor to DerivedComponent?

Removing the dependency from the DerivedComponent seems to result in it not being injected.

There are already similar questions with extensive discussion.

The answer is basically - no, you can't.

Haven't found the others.

you can't remove the constructor from the DerivedComponent class. But with your code, you have two property named 'myService' in DerivedComponent class. You can simplify the constructor :

export class DerivedComponent {

    public constructor(myService: MyService) {
        super(myService);
    }

}

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