Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection in Angular 2 Creates Multiple Instances while using Inline Injector and Constructor Injection

I'm working on a Ionic 2 TypeScript project. During application startup I inject a 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 instance of variables instance1 and instance2.

Is there any possible way to make them as one instance by using the inline Injector and Constructor

like image 814
tymspy Avatar asked May 13 '16 11:05

tymspy


People also ask

What is dependency injection in Angular 2 with example?

Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.

Which object does the Angular injector used to create an instance of dependency?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.

Can we create multiple instances of service in Angular?

It will create multiple instances of a service. Every time a new instance of provided service will be created when a component is used inside another component.

How many ways we can do dependency injection in Angular?

There are three types of Dependency Injections in Angular, they are as follows: Constructor injection: Here, it provides the dependencies through a class constructor. Setter injection: The client uses a setter method into which the injector injects the dependency.


1 Answers

"Singletons" are maintained per provider instance. If you create a new Injector (that's what Injector.resolveAndCreate ( [ MyService ] ); does, then it also has it's own provider instances. Therefore the behavior is expected.

You can inject the Injector to your component and service and create a child injector which then could work as expected.

If you need an injector where you can't inject the Angular injector, there is a workaround explained in this comment (with Plunker) https://github.com/angular/angular/issues/4112#issuecomment-153811572

like image 199
Günter Zöchbauer Avatar answered Nov 15 '22 03:11

Günter Zöchbauer