133

I have a @Injectable service defined in Bootstrap. I want to get the instance of the service without using constructor injection. I tried using ReflectiveInjector.resolveAndCreate but that seem to create a new instance.

The reason I'm trying to do this is I have a base component derived from many components. Now I need to access a service but I don't want to add it to the constructor because I don't want to inject the service on all of the derivative components.

TLDR: I need a ServiceLocator.GetInstance<T>()

UPDATE: Updated code for RC5+: Storing injector instance for use in components

dstr
  • 8,362
  • 12
  • 66
  • 106

6 Answers6

119

In the updated Angular where ngModules are used, you can create a variable available anywhere in the code:

Add this code in app.module.ts

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

export let AppInjector: Injector;
    
export class AppModule {
  constructor(private injector: Injector) {
    AppInjector = this.injector;
  }
}

Now, you can use the AppInjector to find any service in anywhere of your code.

import { AppInjector } from '../app.module';

const myService = AppInjector.get(MyService);
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68
Elias Rezer
  • 1,299
  • 1
  • 8
  • 3
  • 1
    Nice. Might be a good answer at http://stackoverflow.com/questions/39409328/storing-injector-instance-for-use-in-components as well. – Arjan Apr 20 '17 at 16:48
  • 4
    You're the king! – Davide Perozzi Feb 16 '18 at 00:44
  • 2
    Wow are we allowed to do this ? – Simon_Weaver Jun 19 '19 at 19:18
  • 3
    This has a small problem. You have to make separate injectors for lazy loaded modules that provide a service. – Vahid Sep 29 '19 at 14:29
  • 10
    Yeah lets make everything just a global public static monolithic variable. NOT – Youp Bernoulli Feb 16 '21 at 20:16
  • @BernoulliIT I'd argue this makes sense when used in an abstract class - changing the abstract class injectors will not require changing constructors of every single inheritor. This is in line with the open-closed principle. – Vedran Jul 05 '22 at 15:24
  • I don't see this AppModule being an abstract class and furthermore do you mean constructors instead of injectors? If this is so your statement is not true (at least not in Angular) and derived classes do have to provide constructor arguments to be passed through to the super/base class constructor, also when this is an abstract class. – Youp Bernoulli Jul 06 '22 at 12:35
98

Yes, ReflectiveInjector.resolveAndCreate() creates a new and unconnected injector instance.

You can inject Angulars Injector instance and get the desired instance from it using

constructor(private injector:Injector) {
  injector.get(MyService);
}

You also can store the Injector in some global variable and than use this injector instance to acquire provided instances for example like explained in https://github.com/angular/angular/issues/4112#issuecomment-153811572

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Storing injector in a global variable in bootstrap.then() sound like what I need. – dstr May 30 '16 at 11:00
  • 119
    The question says without a constructor which makes this answer rather unhelpful. – Jon Miles Nov 15 '16 at 12:46
  • Without constructor there is no injection. Should we delete the question then ;-) – Günter Zöchbauer Nov 15 '16 at 12:48
  • @GünterZöchbauer, do you know which injector instance is injected when used like this `private injector:Injector`? Is it root injector instance? Or it depends? – Max Koretskyi Feb 16 '17 at 07:09
  • 1
    If the constructor is in a component, it's the components injector, in a service it's the module injector (basically root injector if it's not a lazy loaded module). You can also get the parent components injector by adding `@SkipSelf()`. You can also interate the `parent` getter, to get the root injector. – Günter Zöchbauer Feb 16 '17 at 07:10
  • @GünterZöchbauer, got it, thanks! _it's the components injector_ - even if it's not defined any providers? – Max Koretskyi Feb 16 '17 at 07:12
  • Yes, a component always has some providers, like `ElementRef` registered. There is no component or directive without an injector. An injector always provides its own providers and all providers of parent injectors - just as a note. – Günter Zöchbauer Feb 16 '17 at 07:13
  • I've never seen mentioning that a directive has it's own injector. Do you know where can I read about that? And is my understanding correct that `private injector:Injector` is an instance returned by `ReflectiveInjector.resolveAndCreate`? – Max Koretskyi Feb 16 '17 at 07:15
  • I don't know about docs, but you can register providers on a directive the same as a component. A component is basically just a directive with a view. If a directive is added to a component they share providers (don't know how this is exactly implemented). Yes, I'm pretty sure a components injector is built this way. – Günter Zöchbauer Feb 16 '17 at 07:20
  • @GünterZöchbauer It didn;t work for me with `opaqueTokens`. I've Already asked [here](http://stackoverflow.com/questions/43286665/angular2-injecting-opaquetoken-provider-to-a-regular-class) . I'm hoping to find a solution – Royi Namir Apr 07 '17 at 20:46
  • This just puts something else in the constructor. How do you get it without a constructor. – Rhyous Aug 28 '18 at 17:19
  • 2
    @Rhyous magic? You can share the injector in a static field or global variable and access it from there, but first you need to inject it "somewhere" using a constructor and assign it to the static field. – Günter Zöchbauer Aug 28 '18 at 17:22
  • 1
    Is the DI container ng uses that bad, that it doesn't even support the basic features of a common DI container? – Rhyous Aug 28 '18 at 17:27
  • @GünterZöchbauer That isn't an answer, that is an excuse. – Rhyous Aug 28 '18 at 17:37
  • Why would I want to spend my time for someone who downvotes my answer just becuase he wants something else? – Günter Zöchbauer Aug 28 '18 at 17:41
  • Hi, injector.get(ViewContainerRef) is returning null in my case. Could you please reply me with the possible situations if any to return null. – Nanda Kishore Allu Apr 27 '21 at 08:39
  • Thank you. I`m using this variant, too. This is not an exact answer to the question because Injections needs to be passed by constructor. But it is much better than adding every needed service to the base class and then have to change all classes deriving it if I need another service. So this is a great answer. – user1383029 Apr 13 '23 at 12:21
7

Another approach would consist of defining a custom decorator (a CustomInjectable to set the metadata for dependency injection:

export function CustomComponent(annotation: any) {
  return function (target: Function) {

    // DI configuration
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    var parentAnnotations = Reflect.getMetadata('design:paramtypes', parentTarget);

    Reflect.defineMetadata('design:paramtypes', parentAnnotations, target);

    // Component annotations / metadata
    var annotations = Reflect.getOwnMetadata('annotations', target);
    annotations = annotations || [];
    annotations.push(annotation);
    Reflect.defineMetadata('annotations', annotations, target);
  }
}

It will leverage the metadata from the parent constructor instead of its own ones. You can use it on the child class:

@Injectable()
export class SomeService {
  constructor(protected http:Http) {
  }
}

@Component()
export class BaseComponent {
  constructor(private service:SomeService) {
  }
}

@CustomComponent({
  (...)
})
export class TestComponent extends BaseComponent {
  constructor() {
    super(arguments);
  }

  test() {
    console.log('http = '+this.http);
  }
}

See this question for more details:

JeremyEastham
  • 177
  • 2
  • 11
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • 2
    The problem is tsc doesn't let me call super(arguments) because the arguments for the base constructor don't match. – parliament Nov 10 '16 at 18:36
  • 1
    in that particular case we can just remove constructor from derived class https://github.com/Microsoft/TypeScript/issues/12439 – slowkot Jul 05 '17 at 10:43
1

Angular 14 introduced an inject function.

According to the documentation

In practice the inject() calls are allowed in a constructor, a constructor parameter and a field initializer:

@Injectable({providedIn: 'root'})
export class Car {
  radio: Radio|undefined;
  // OK: field initializer
  spareTyre = inject(Tyre);

  constructor() {
    // OK: constructor body
    this.radio = inject(Radio);
  }
}

And

It is also legal to call inject from a provider's factory:

providers: [
  {provide: Car, useFactory: () => {
    // OK: a class factory
    const engine = inject(Engine);
    return new Car(engine);
  }}
]

In your case you can therefore use

class MyClass {
serviceLocator = inject(ServiceLocator)
}
Flavien Volken
  • 19,196
  • 12
  • 100
  • 133
0

After running into this issue a few times, I've devised a good way to overcome it by using a getter with the Angular Injector service, instead directly injecting the service in the constructor. This allows the service time to be constructed before being referenced. My example uses only services but the same thing can be applied to a component using a service, just put the getter in a component instead BService in the example.

What I did was use a getter to inject the service into a class property using the Injector class, if the class property was not already set before, so the service is only ever injected once (the first time the getter is called). This allows the service to be used in basically the same way as if it was injected in the constructor but without a circular reference error. Just use the getter this.aService. They only time this won't work is if you are trying to use AService within the constructor of Bservice, then you would have the same issue of a circular reference since Aservice would not be ready yet. By using the getter you are deferring injecting the service until you need it.

There are arguments that, AService depending on BService, and BService depending on AService, is bad form but there exceptions to every rule and every situation is different so this is an easy and effective way to deal with this issue in my opinion.

// a.service.ts
import { Injectable } from '@angular/core';

import { BService } from './b.service';

@Injectable({
  providedIn: 'root'
})
export class AService {

  constructor(
    private bService: BService,
  ) { }

  public foo() {
    console.log('foo function in AService!');
    this.bService.bar();
  }
}
// b.service.ts
import { Injectable, Injector } from '@angular/core';

import { AService } from './a.service';


@Injectable({
  providedIn: 'root'
})
export class BService {
  // Use the getter 'aService' to use 'AService', not this variable.
  private _aService: AService;

  constructor(
    private _injector: Injector,
  ) { }

  // Use this getter to use 'AService' NOT the _aService variable.
  get aService(): AService {
    if (!this._aService) {
      this._aService = this._injector.get(AService);
    }
    return this._aService;
  }

  public bar() {
    console.log('bar function in BService!');
    this.aService.foo();
  }
}
RcoderNY
  • 1,204
  • 2
  • 16
  • 23
-3

StoreService .ts

  import { Injectable} from '@angular/core';
    
    @Injectable()
    export class StoreService {
      static isCreating: boolean = false;
      static instance: StoreService ;
    
      static getInstance() {
        if (StoreService.instance == null) {
          StoreService.isCreating = true;
          StoreService.instance = new StoreService ();
          StoreService.isCreating = false;
        }
        return StoreService.instance;
      }
      constructor() {
        if (!StoreService.isCreating) {
          throw new Error('You can\'t call new in Singleton instances! Call StoreService.getInstance() instead.');
        }
     }
    
  MyAlertMethod(){
    alert('hi);
    }
  }

.ts

//call this service directly in .ts as below:-

 StoreService.getInstance().MyAlertMethod();
Mahi
  • 3,748
  • 4
  • 35
  • 70