I have user data like 'cart with clothes to buy'. I have a shop screen in which the user fills the cart. The requirement is if i am on that screen and fill the cart to persist it while user goes to the checkout screen. Meanwhile he can go to my account, my settings, add new address, add new credit card screens and when he goes to pay order screen or again back to the cart i should fill those screens with the data previously chosen in the first visit of the shop screen. I considered putting it into some global common.service.ts in my main app module (which loads all other modules) buut when i refresh the page the data is not persisted... The only idea i come up with is to use the cookies and clear them on logout or they will auto clear when the tab is closed, but this solution does not feel right to me at the moment so i seek for a better approach.
2 Answers
You should definitely use a service to make the data accessible to all of your components and "pages". For data persistence across browser refreshes you could use either cookies or local storage. My preference for this type of data is local storage because you can represent your data as JSON and then use JSON.stringify
and JSON.parse
to save and retrieve your data respectively.
The general strategy would be to always use the in memory data when it is available. Every time the data is modified save the new version to local storage. When the service first starts up it should load the previous data from local storage.
Another potential option would be to save this information in a database following a similar strategy to the one defined above for local storage. A benefit of using a database is that the data can be persisted across browsers which you cannot do using local storage.

- 13,774
- 2
- 46
- 51
When looking at storing state in Angular 2 a popular tool is redux (https://www.npmjs.com/package/ng2-redux) and you can use that to store and access state in a session and combine that with the answer from this question (Where to write to localStorage in a Redux app?) you can subscribe to changes in the edux store and save them into local storage as they happen. It is a pretty solid pattern and allows for a lot of great things (for a cart for instance you can replay state so if a user removes something from the cart then wants it back it is really easy).

- 1
- 1

- 943
- 15
- 22