Dependency Injection in Angular 2 Creates multiple instances when using Inline Injector and Constructor Injection

I am working on an Ionic 2 TypeScript project. When the application starts, I enter the service through the constructor.

@App({ providers: [ MyService ] }) export class MyApp { constructor( private instance1 : MyService ){} } 

And in another class I use

 let injector = Injector.resolveAndCreate ( [ MyService ] ); let instance2 = injector .get( MyService ); 

I get two different instances of the variables instance1 and instance2.

Is there any possible way to make them a single instance using the built-in injector and constructor

+8
angularjs dependency-injection angular typescript ionic-framework
source share
2 answers

Singletones are supported for each instance of the provider. If you create a new Injector (what Injector.resolveAndCreate ( [ MyService ] ); , then it also has its own provider instances, so behavior is expected.

You can inject Injector into your component and service and create a child injector that can then work as expected.

If you need an injector in which you cannot inject an Angular injector, this comment (using Plunker) describes a workaround https://github.com/angular/angular/issues/4112#issuecomment-153811572

+2
source share

Use the resolveAndInstantiate method:

 let instance2 = injector.resolveAndInstantiate(MyService); 
0
source share

All Articles