Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs 4 - Inject a service without passing parameters on the constructor

Is there a way to inject a service into a class without having to declare it as a parameter on the constructor?

The usual way works just fine, I have no complains about it. I'm just trying to create a super class to handle some stuff witch depends on a service and I want it to be independent, I don't want to have any references to that service on child classes.

This is the usual way:

export class MyComponent {
  constructor(private someService: SomeNpmInstalledService) {}

  doSomething() {
    this.someService.do();
  }
}

That's what I'm looking for:

export class MyComponent {
  @Some injection magic annotation here
  private someService: SomeNpmInstalledService;

  constructor() {}

  doSomething() {
    this.someService.do();
  }
}

I'll try to explain the reason why I want this kind of functionality with the following example:

export class MyComponent extends MySuperClass {
  constructor() {
    super();
  }

  doSomething() {
    super.someSuperClassFonctionality(); 
  }
}

export class MySuperClass {
  constructor(private someService: SomeNpmInstalledService) {}

  someSuperClassFonctionality() {
    someService.doStuff(); 
  }
}

The above code gives an error because in my component, when I call super(), I have to pass the parameter defined on the constructor of my super class. But That's exactly what I don't want to do. I want my components to don't even know about the service that is used inside the super class.

like image 861
João Carreira Avatar asked Oct 02 '17 16:10

João Carreira


1 Answers

Yes: use Injector. https://angular.io/api/core/Injector

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

then in your constructor:

constructor(injector: Injector) {
  let this.service = injector.get(ServiceToInject);
}
like image 106
hayhorse Avatar answered Nov 01 '22 05:11

hayhorse