1

I have three classes (or more) with the followings inheritance:

  • class A (abstract class)
  • class B extends A
  • class C extends B

I want to add a service in the class A to implement a function that use notifications, how can I do this without adding in any sub-classes the service?

My solution is similar to this draft but I would avoid to import the service in the subclasses:

export class abstract A {
  constructor(protected service: NewService) {}
}

export class B extends A {
  constructor(protected service: NewService) {
    super();
  }
}

export class C extends B {
  constructor(protected service: NewService) {
    super();
  }
}
Stefano Borzì
  • 1,019
  • 1
  • 15
  • 32

1 Answers1

0

I think the only (universal) way of doing that is by passing an Injector into abstract class. Then you can inject any number of services into it. After that you should pass injector into super() call of every descendant class.

import { Injector } from '@angular/core';

export abstract class Base {
  private serviceA: ServiceA;
  private serviceB: ServiceB;

  constructor(
    injector: Injector,
  ) {
    this.serviceA = injector.get(ServiceA);
    this.serviceB = injector.get(ServiceB);
  }
}

export class Child extends Base {
  constructor(
    private injector: Injector,
  ) {
    super(injector);
  }
}
an-angular-dev
  • 301
  • 3
  • 5