Thank you so much for sharing this.

Component and theirs children component share the *same instance* of a 
service, *if *the service was provided in the Component.

My problem was to share it in the whole app, so i provided it in bootstrap.

Le mardi 3 novembre 2015 01:26:50 UTC+1, Eric Martinez a écrit :
>
> Ben,
>
> like Pascal commented in that article, everything is a singleton already.
>
> Let's see it with a few examples
>
> class Service {}
>
> @Component({})
> class MyComponent {
>  constructor(svc: Service) {}
> }
>
> bootstrap(MyComponent, [Service]);
>
>
> At this point Service is the same instance for the entire application. So 
> if you have N components listen to this service, and one of them modifies 
> something in it, all of them will be aware of that change.
>
> Now, what if I want Service to be visible in just one component? So you 
> use "providers"
>
> class Service {}
>
> @Component({})
> class ChildCmp {
>  constructor(svc: Service) {} // Same instance as in the parent
> }
>
> @Component({ providers : [Service], directives : [ChildCmp]] })
> class MyComponent {
>  constructor(svc: Service) {}
> }
>
> @Component({})
> class AnotherComponent {
>  constructor(svc: Service) {} // <<< FAIL! Has no provider for Service!
> }
>
> bootstrap(MyComponent); // Removed [Service], now it lives in the 
> component 
>
>
> With this Service is visible only to the component itself and its children 
> and all of them will share the same instance. 
>
> Well, again, what if I want my main component have one instance and its 
> children have another one? Very simple, you just override the instance by 
> specifying providers in the children component.
>
> class Service {}
>
> @Component({ providers : [Service] }) // Override parent's Service 
> instance
> class ChildCmp {
>  constructor(svc: Service) {} // This instance is not the same as the 
> parent
> }
>
> @Component({ providers : [Service], directives : [ChildCmp] })
> class MyComponent {
>  constructor(svc: Service) {}
> }
>
>
>
> In short : Just specify the Service once for the parent component and the 
> component itself and all of its children will share the same instance and 
> everytime you want a new instance just override it by passing it through 
> providers :D
>
> I  hope I was clear enough.
>
> Read this article (I haven't read it, shame on me), but I'm pretty sure it 
> will clarify much more things for you
>
> http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to