Reputation: 4270
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
Upvotes: 8
Views: 829
Reputation: 658067
"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
Upvotes: 2