Is it possible to save classes to Native Storage?


When I use the Native Storage Plugin, I can save data in the local storage.

You can also store classes, but the functions will not be callable after loading from the database.

Look at this example

export class TestClass{

    test(): void{

For example somewhere in the Code I write

this.localDb.set("class", this.testClass)

where localDb is the Instance of Storage and testClass is the Instance of TestClass.

Somewhere later I want to get that value from the database again like this:

this.localDb.get("class").then((class: TestClass)=>{

class.test() should simply log "test", but instead you get

Runtime Error
class.test is not a function

Can you somehow work around this behaviour?

My only solution would be to put the test function in a class that is not saved to the database (Thats also what I did in my case) - but is there something else you can do? Because for me it was a function that did logically belong into the saved class.


All that gets persisted to storage is the result of JSON.stringify, so “no, not really”. You could hack around it, but I don’t think it’s worth the effort. Especially in a language such as JavaScript that has no real OO support, I think you are better off with dumb data and smart handlers. IOW, I would make all data-holding stuff interfaces instead of classes, and move all the logic into providers instead. In addition to making life with storage easier, it also will translate well to situations where you are slinging data around with HTTP.