2

It seems that each component that creates its own instance of [a] service. I don't understand why.

I note this AngularJs 2 - multiple instance of service created, but I'm not clear on the correct solution. Do I create the service instance _myService in main:

 void main() {
  bootstrap(AppComponent,[MyService]);
 }

and then copy it to [child] components (because I also remove MyService from the component providers)? This doesn't seem correct, because the components reference _myService before it's instantiated, and I have to check it for being null.

Thanks

Steve

Community
  • 1
  • 1
Lymp
  • 933
  • 1
  • 7
  • 20

2 Answers2

1

You can use factory constructor pattern like here.

biv
  • 96
  • 5
0

Creating your service in the bootstrap will make sure there is only one instance of it for the app (if you don't provide it again in some component).

You get multiple copies of it only if you provide it in some @Component - then each instance of the component (and all its children) will have a separate instance of the service.

rkj
  • 8,787
  • 2
  • 29
  • 35
  • "Creating your service in the bootstrap will make sure there is only one instance of it for the app." - but it doesn't. I get several intances. So, if I remove MyService from component providers, how do the components access the instance from the bootstrap? Thanks,s – Lymp Apr 22 '17 at 10:38
  • DI is closely related to the DOM tree in Angular - if you provide something on the app level any component can Inject it. – rkj Apr 23 '17 at 06:08