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
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.
The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.
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.
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.
"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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With