Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting instance of service without constructor injection

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 is I have a base component derived by many components. Now I need to access a service but I don't want to add it to the ctor 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

like image 554
dstr Avatar asked May 27 '16 11:05

dstr


People also ask

How do you inject a service without a constructor?

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.

Can we use service without injectable?

If you want to use angular services (and Http is an angular service) you must inject them as I told above as a constructor attribute to another service / component , which means if you want to use Http you need to have your service injectable. So the answer is no, you can't do it in a nice way.

Can we get a service instance without dependency injection in the Controller action method?

The bottom line is: you don't have to forego dependency injection. You can define & implement interfaces in different layers.

Can we use service without dependency injection in Angular?

If no Angular decorator has been used on a class there is no way for Angular to read what dependencies it requires. This is why we need to use @Injectable() . If our service injects providers we must add @Injectable() , which providers no extra functionality, to tell Angular to store that metadata it needs.


1 Answers

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); 
like image 90
Elias Rezer Avatar answered Sep 21 '22 06:09

Elias Rezer