60

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.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Kamil Lelonek
  • 14,592
  • 14
  • 66
  • 90
  • You need to inject FetchApi into the inheriting class, but if it helps, you can access it from the base class doing something like `( this).fetchapi.call(...)` (you don't need to explicitly pass it via `super()`. – rinogo Jan 06 '17 at 22:43

4 Answers4

83

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();
  }
}
Petr Marek
  • 1,381
  • 1
  • 15
  • 31
  • How can i inject a service from child, and use it from parent? – Haidang Nguyen Feb 07 '17 at 09:23
  • I think that you cannot and it doesn't make sense to me. What is your use-case? – Petr Marek Feb 09 '17 at 10:13
  • 8
    I'm with Petr - as far as I know, parent classes are not at all aware of anything in their subclasses. That'd be like the Roy Scheider's character from Jaws knowing what happens to Michael Caine in Jaws: The Revenge. And I insist this is a perfect analogy. – SilithCrowe Mar 15 '17 at 18:11
  • 1
    Great method!! solve my problem. According to this feature of angular 2.3, I think I can migrant all the programme pattern of Java to the angular to reduce a lot of duplicate code! – Xin Meng Mar 31 '17 at 15:46
  • 1
    I love this solution and it works like a charm. I haven't tested it with different production builds though. Will this work with tree-shaking? – therebelcoder Apr 23 '17 at 22:25
  • 2
    @PetrMarek seems like service injected by this solution create instance different from usual inject by constructor. That's true? It's not a big problem, but if i want use this solution only for inheritance, is there a way to use the same instance as usual from constructor? – Sano Litch Jun 04 '18 at 10:10
  • Hi, what about if FetchApi also has dependencies like TranslateService or AlertController in controller and need injection? How can we implement that? – Okan SARICA Mar 15 '19 at 18:39
56

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.

rafaelbattesti
  • 562
  • 4
  • 13
TGH
  • 38,769
  • 12
  • 102
  • 135
  • 1
    This is what I read too. I wanted to abstract DI to avoid this entire boilerplate, but I see that I need to import, inject and extend subclasses in almost the same way. – Kamil Lelonek Nov 28 '15 at 21:03
  • 1
    I don't understand this. By "base class" do you mean "derived class" (normally "base class" would be the same as "superclass")? Where in your example is `fetchAPI` being "passed"? Are you saying that if I construct a new derived class the injections called for in the superclass will be made? –  Jun 28 '16 at 12:18
  • 7
    _"This is a feature of how DI works in general"_ - in general in angular, but not in general everywhere. Many frameworks support DI through properties binding. – Qwertiy Oct 04 '16 at 10:09
  • 9
    I'm experiencing a problem with this answer: Adding a new injected service to the super class will break all of the subclasses unless you update the super() call in each of their constructors with the same new parameter. This isn't ideal if you're developing a package library and won't necessarily have access to the classes inheriting from your own. Not sure if there's a way around this, but I'm open to suggestions! – SilithCrowe Mar 15 '17 at 18:06
41

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);

}
Rogerio
  • 411
  • 4
  • 3
2
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

zyn
  • 21
  • 2