6

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.

  • How you gonna use it without injecting in constructor? – P.S. Oct 02 '17 at 16:53
  • 1
    Possible dupe: https://stackoverflow.com/q/45225676/3001761 – jonrsharpe Oct 02 '17 at 16:59
  • Thanks jonrsharpe. It's almost the same yes, but I'n my case I would need the injector to be injected in an other way then be declared in the constructor (if possible) – João Carreira Oct 04 '17 at 16:35
  • I ran into this issue a couple of projects before. I ultimately decided that there was no clean way of doing this, and I instead just made two services and injected the "superclass" service into the "subclass" service in its constructor and used it as a parallel service. – hayhorse Oct 04 '17 at 22:32
  • Thanks for the reply hayhorse. That was my backup approach too but was wondering if someone else had a nice alternative to it. – João Carreira Oct 05 '17 at 17:44

1 Answers1

1

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);
}
hayhorse
  • 2,652
  • 1
  • 10
  • 7