How to extend a component with dependency injection?

Dependency InjectionAngular

Dependency Injection Problem Overview


I have the following class ModuleWithHttp:

@Injectable()
export default class {
  constructor(private fetchApi: FetchApi) {}
}

and I want to use it as follows:

@Component({
  selector: 'main',
  providers: [FetchApi]
})
export default class extends ModuleWithHttp {
  onInit() {
    this.fetchApi.call();
  }
}

So by extending a super class that already injects a dependency I want to have an access to it in its children.

I tried many different ways, even having super-class as a component:

@Component({
  providers: [FetchApi]
})
export default class {
  constructor(private fetchApi: FetchApi) {}
}

But still, this.fetchApi is null, even in super-class.

Dependency Injection Solutions


Solution 1 - Dependency Injection

If you want to avoid this "boiler plate" code injecting services in child classes just for injection in parent classes' constructor and then effectively using that services in child classes through inheritance, you could do this:

edit: from Angular 5.0.0 ReflectiveInjector has been deprecated in favour of StaticInjector, below is updated code to reflect this change

Have a services map with deps,

export const services: {[key: string]: {provide: any, deps: any[], useClass?: any}} = {
  'FetchApi': {
    provide: FetchApi,
    deps: []
  }
}

Have an Injector holder,

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

export class ServiceLocator {
  static injector: Injector;
}

set it up in AppModule,

@NgModule(...)
export class AppModule {
  constructor() {
    ServiceLocator.injector = Injector.create(
      Object.keys(services).map(key => ({
        provide: services[key].provide,
        useClass: services[key].provide,
        deps: services[key].deps
      }))
    );
  }
}

use the injector in parent class,

export class ParentClass {

  protected fetchApi: FetchApi;

  constructor() {
    this.fetchApi = ServiceLocator.injector.get(FetchApi);
    ....
  }
}

and extend parent class so you don't need to inject the FetchApi service.

export class ChildClass extends ParentClass {
  constructor() {
    super();
    ...
  }

  onInit() {
    this.fetchApi.call();
  }
}

Solution 2 - Dependency Injection

You have to inject fetchAPI in the super class and pass it down to the child class

export default class extends ModuleWithHttp {
  
  constructor(fetchApi: FetchApi) {
     super(fetchApi);
  }   
  
  onInit() {
    this.fetchApi.call();
  }
}

This is a feature of how DI works in general. The super class will instantiate the child via inheritance, but you have to supply the required parameters to the child.

Solution 3 - Dependency Injection

Maybe late response, but I had resolved injecting only the injector on the BaseComponent and in all subclasses, that way I do not need to maintain a service locator.

My base Class :

constructor(private injectorObj: Injector) {

  this.store = <Store<AppState>>this.injectorObj.get(Store);
  this.apiService = this.injectorObj.get(JsonApiService);
  this.dialogService = this.injectorObj.get(DialogService);
  this.viewContainerRef = this.injectorObj.get(ViewContainerRef);
  this.router = this.injectorObj.get(Router);
  this.translate = this.injectorObj.get(TranslateService);
  this.globalConstantsService = this.injectorObj.get(GlobalConstantsService);
  this.dialog = this.injectorObj.get(MatDialog);
  this.activatedRoute = this.injectorObj.get(ActivatedRoute);
}

My Child Classes :

constructor( private injector: Injector) {

   super(injector);

}

Solution 4 - Dependency Injection

export class MyBaseClass {

  injector = Injector.create({
    providers: [
      { provide: MyService1, deps: [] },
      { provide: MyService2, deps: [] }
    ]
  });

  constructor() {
    this.myService1 = this.injector.get(MyService1);
    this.myService2 = this.injector.get(MyService2);
  }
}

export class MyChildClass extends MyBaseClass {
  constructor() {
    super();
    // this.myService1 is accessible
    // this.myService2 is accessible
  }
}

Take note though that MyService1 & MyService2 are new instances created by MyBaseClass

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKamil LelonekView Question on Stackoverflow
Solution 1 - Dependency InjectionPetr MarekView Answer on Stackoverflow
Solution 2 - Dependency InjectionTGHView Answer on Stackoverflow
Solution 3 - Dependency InjectionRogerioView Answer on Stackoverflow
Solution 4 - Dependency InjectionzynView Answer on Stackoverflow