Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular inject service into base class but not in sub-class and use the parent service in sub-classes

Using Angular 7 & Typescript: I have a base class that uses a lot of services and child classes (about 40 sub-class) and I don't want to add those services in all subclass constructor and pass them to super() but I still need to use those services in all subclass.


export class parentTool {

    constructor(type: string, public service1: Service1, public service2: Service2,public service3: Service3, public service4: Service4){}
}

export class ChildTool1 extends parentTool {

    constructor(public service1: Service1, public service2: Service2,public service3: Service3, public service4: Service4) {

        super("tool1", service1, service2, service3, service4);
    }
}

export class ChildTool2 extends parentTool {

    constructor(public service1: Service1, public service2: Service2,public service3: Service3, public service4: Service4) {

        super("tool2", service1, service2, service3, service4);
    }
}
like image 531
amira Avatar asked Jun 25 '19 07:06

amira


People also ask

Can a service inject another service Angular?

Yes, the first thing is to add the @Injectable decorator on each services you want to inject.

What happens when injecting a service to the constructor without access modifier?

while injecting the service in your component if you miss the access modifier it will give you error as given below, but adding it as private or public will run fine.


1 Answers

I use to have the same problem so I end up doing manulay DI (dependency injection) by using injector service

this static class use to store a refrence of injector service

export class AppInjector {

  private static injector: Injector;

  static setInjector(injector: Injector) {
    AppInjector.injector = injector;
  }

  static getInjector(): Injector {
    return AppInjector.injector;
  }
}   

at app module I set the injoctor service

export class AppModule { 
  constructor(injector:Injector){
      AppInjector.setInjector(injector);// save a injector ref 💾
  }
}

you need to store the service before you start do any DI (dependency injection)

in the base component

export class BaseComponent {
  protected utilitiesService: UtilitiesService; // 👈 service
  protected loggingService: LoggingService; // 👈 service

  constructor() {

      const injector = AppInjector.getInjector();

      this.utilitiesService = injector.get(UtilitiesService); // 🌟 DI
      this.loggingService = injector.get(LoggingService); // 🌟 DI


  }

}

child class now have access to all service injected by the injector class 🎉🎉

    export class ChildComponent extends BaseComponent {
      constructor() {
        super();
      }
    }

demo 🔥🔥

like image 84
Muhammed Albarmavi Avatar answered Sep 18 '22 16:09

Muhammed Albarmavi