Darren Mitchinson
Darren Mitchinson

Reputation: 81

Angular 2 update components using a service

I have created a simple app containing 2 components and a service to show how to add items to a basket by having one component update a value in a service which the other component has subscribed to. Using this Plunker example you can see the service gets updated values but when you click the value of the basket you will see the number of items in the basket on the component stays at 0 (using console.log). How do I get the component to match the same values as the service?

I think it could be because my main page is like this, so its treating the components as seperate apps therefore creating 2 services. I dont want to have all my angular components in one root app.

   <body>
    <div>
      Basket Holder<fc-basket>loading basket...</fc-basket><br/><br/>
    </div>
    <my-app>
    loading...
  </my-app>
  </body>`

Upvotes: 0

Views: 290

Answers (1)

Aniruddha Das
Aniruddha Das

Reputation: 21688

The problem was you have provided the basketService 3 times and there were 3 instances of the basket service with their own subscribe flow.

  • at the app module level when you defined at app.module
  • at the individual component level

you don't need to provides[service] in you component if you already did it in your module. or else it will create another instance rather using the module level instance

I resolved your plunker at resolved plunker

Upvotes: 2

Related Questions