Wednesday 27 January 2016

Are Angular 2 Services Singletons?


No.
Like in Angular 1, a "Service" service news up the function we use to define it.

If they were singletons, this approach would work.

JS Bin on jsbin.com

That jsbin sets up a service that holds a list, and injects it into two different components.  One displays the list, the other adds items to it.
As we can see, it doesn't work.
As we can also see in the console, the constructor is called twice, once for each component Demo1Service is injected to.

This is how we have to do it for it to work:

JS Bin on jsbin.com
Now the list is outside the class and each instance of that service will have a reference to the same array.

Let's see if I'm getting something wrong, and it's all coming from my using ES5 or something.

How about JScript  TypeScript?

It still news up the class twice, so it doesn't work properly with the array as a member of the class: http://plnkr.co/edit/UwZ0d6g2X5NAV5J5j7rS?p=preview

And it works fine with the list outside, of course: http://plnkr.co/edit/78eXH0oJIwqS9WocyjGn?p=preview

Then why can't I find anywhere on the internet anybody that says the same thing?

This post appears to me to be saying the exact opposite of this.  That all services are Singletons: http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

That is right now being linked to from the official Angular 2 docs.  It doesn't bode well.

No comments:

Post a Comment