1

I have created a singleton class in Angular2 and it works fine . I was able to store some values and use those in the child components. But the issue is that when i refresh the browser the singleton class is recreated and the old object is gone. Is thier any way i can persist those values even after the browser refresh. It would be a life saver if anyone can help me. Thanks in advance.

Note: I dont want to use localstorage or sessionstorage since their is a lot of information to store.

vinton
  • 49
  • 6
  • With session storage, you meant cookie? – Lucio Sep 24 '15 at 05:15
  • HTML5 localstorage , sessionstorage – vinton Sep 24 '15 at 19:28
  • Then just use cookies. – Lucio Sep 24 '15 at 19:31
  • 2
    Your best options are the options you don't want to use. When you refresh the webpage everything is refreshed and you lose all you have in memory. So just use them, [see this answer](http://stackoverflow.com/questions/23127498/persisting-values-in-javascript-object-across-browser-refresh). If you are in a nodejs environment you could use mongo with mongoose. – Eric Martinez Sep 24 '15 at 21:08
  • Thanks Erik. Right now i am using sessionstorage to store the context information. But my manager says that we are storing lot of information on the session storage which is bad . In this case i think i need to think about mongodb as you said .. – vinton Sep 25 '15 at 01:36

2 Answers2

2

IndexedDB sounds like a good solution to me.

Check canIuse for browser support.

You may create an angular service that exposes some methods such as

  • writeData(key, data)
  • readData(data)
  • deleteData(key)

Since IndexedDB is asynchronous, I suggest that you make those methods return promises to have a clean API.

Once you have such a service, you basically have an angular generic data persistence layer on the browser with quite a lot of storage.

LocalStorage est quite limited (5MB on some platforms) while indexedDB usually offers a lot more storage space. It still depends on the user's browser and OS.

PS: you might want to edit your question since your problem is more about data storage than it is about the singleton pattern

0

as other pointed out localstorage or IndexedDB sound like the way to go.
If your data is to big to be stored there, then it probably does not make sense to store it on the client side anyway.

Then it might make more sense to store this in a simple api like firebase (https://github.com/angular/angularfire).

And out of curiosity where is this data coming from? If you have control over the origin, proper request cache headers could also be a good solution

Nicolas Gehlert
  • 2,626
  • 18
  • 39