2

In my quest to learn Angular2, i came across the following situation:

  • 1 base class, which uses the angular2/http dependency
  • 1 inheriting class which extends the base class

How can I inject the angular2/http dependency in the base class's constructor, without having to pass http as a parameter when instantiating the inheriting class.

I don't use http in the inheriting class, so I don't want to see it there!

For example

// base class
class CRUDService {

    // http is used in this service, so I need to inject it here
    constructor(@Inject(Http) http) {}

    findAll() {
        return this.http.get('http://some.api.com/api/some-model');
    }
}

// inheriting class
class ThingService extends CRUDService {

    constructor() {
        // because we extend the base class, we need to call super()
        // this will fail since it expects http as a parameter
        // BUT i don't use http in this class, I don't want to inject it here
        super();
    }
}

Ideally, I would just create a new http instance in the base class and use that like so let http = new Http();, but that obviously doesn't work.

Sander
  • 103
  • 8
  • You need to inject it into the inheriting class, but if it helps, you can access it from the base class doing something like `( this).http.get(...)` (you don't need to explicitly pass it via `super()`. – rinogo Jan 06 '17 at 22:41

1 Answers1

1

That's not supported. If you want inject something you have to list it in the constructor of the sub-class and if you want to pass it to the super-class you can by using super(someDependency). There is no way around.
That's not an Angular limitation but a language limitation that is quite common among typed classes.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I'm trying to wrap my head around this. It seems utterly ridiculous to me at this juncture... :( – Tyguy7 Feb 06 '17 at 01:22
  • I have heard this a lot. There is nothing Angular can do about it, that'ts how constructors in TS (and many other languages) work. If the subclass doesn't have a constructor at all, then the constructor of the superclass is used, but if the subclass has a constructor, all parameters need to be repeated and passed to `super()`. – Günter Zöchbauer Feb 06 '17 at 04:02