Lymp
Lymp

Reputation: 973

How to avoid multiple instances of a service in Angular Dart

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

Upvotes: 2

Views: 615

Answers (2)

biv
biv

Reputation: 96

You can use factory constructor pattern like here.

Upvotes: 1

rkj
rkj

Reputation: 9311

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.

Upvotes: 0

Related Questions