0

Angular 8

So the point of extending a base class is so child classes have methods provided by the parent class. However, base class needs some injections of various services. Those services are not needed by the chind classes. Example:

// The parent class which will be extended by the many children 
export class parentClass {
  constructor(private service1: service1Service) {
  }

  protected action1(): any {
    return this.service1.someFunc();
  }

  public action2(): any {
    return this.service1.someFunc2();
  }
}

// One of the child classes which doesn't care about service1Service, but is required to inject it anyway...
export class childClass extends parentClass {
  constructor(service1: service1Service) {
    super(service1);
  }

  public doSomething() {
    const data = this.action1();
    // bla bla bla
  }
}

So the big problem is that every child class must inject that service1Service even tho they don't need it at all.

My question is: is there a way to inject services inside parent class without requiring them to be injected inside childern? The example above is very simplified. In real situation parent class will have about 5 services injected. The parent class is going to be used by different team members who really should not care about services used there, because they are building their own classes on top of parent class and uses parent methods to retrieve data or perform calculations.

I know there may be one semi good option:

import { Injector } from '@angular/core';
export class parentClass {
  constructor(private injector: Injector) {}
  protected action1(): any {
    const s1 = this.injector.get(service1Service);
    return s1.someFunc();
  }
}

import { Injector } from '@angular/core';
export class childClass extends parentClass {
  constructor(injector: Injector) {
    super(injector);
  }
}

This way children only need to know to inject Injector and pass that to parent constructor. But i still want even cleaner solution, if possible.

Deerjon
  • 59
  • 7
  • Maybe this helps? https://stackoverflow.com/questions/42461852/inject-a-service-manually/42462579#42462579 – MikeOne May 02 '20 at 11:52
  • Yes, that one answer was exactly what i needed. So basically, my question should be marked as "similar". – Deerjon May 04 '20 at 05:41

0 Answers0