crait
crait

Reputation: 156

Proper Way To Share Data Across Components Through Service That Automatically Updates

I am currently trying to implement a system where a user can log in on a web page and view some stats for their account. There is a component for a login form and a component for the stats. I know this could be implemented in one component, but this will be necessary for the project later on.

Both components are connected to the Session Service, which has a User object. Whenever you log in, the login component calls a function in the Session Service, which will go off and validate everything and populate the data inside of the User object appropriately.

I have an ngIf inside of the Stats Component Template that checks the User object in Session Service if the object is populated. If it is, it should display a stat table with information from within that User object.

Currently, I can log in and populate information inside of the Login Form Template, but the Stats Table Template does not update accordingly. I am sure the Session Service is not passing the updated information over to the Stats Component, but I'm not sure why.

Without me posting all the code I use, how would be the correct way to handle this? I think there should be a 2-way binding solution for this, but I have also seen people talk about making the User object observable, which I am not confident I understand. Additionally, I have seen people say that because JavaScript passes values by reference, the object within Session Service would be watched by the components.

Any help understanding this aspect of Angular2 would be very helpful! Thank you very much!

Upvotes: 0

Views: 167

Answers (1)

LLL
LLL

Reputation: 3771

You could have your components communicate through a service with an observable.

Upvotes: 1

Related Questions