I want to have a page-reload proof class instances in my Angular 2 application.
In my component's .ts file I have classes:
export class AComponent implements OnInit {
foo: Foo = new Foo();
ngOnInit() {
// This will always be 12, it would be nice if it would increase with each page refresh.
this.foo.bar.baz += 1;
console.log("baz: " + this.foo.bar.baz);
}
}
class Bar {
baz: number = 11;
}
class Foo {
bar: Bar = new Bar()
}
I know that the localStorage
ES6 thing can store strings. Do I have to write my own deserialization of complex class objects?
Like (I think) suggested here: Angular 2 map http response to instance of class
I would suggest with angular-2-local-storage node_module.
Steps:
npm install angular-2-local-storage
Import the module and service as below
Add the module to imports array and service to providers array as
Inject the Service as a dependency into component as below
LIVE DEMO
using
localStorage
you can do this:with
localStorage
you can store whatever complex object you want.hope this helps!
Your Problem
I am not understanding exactly what you are trying to do with the counter. So I went ahead and made you a real simple example of a way to manipulate your counter and save it to the
localStorage
.In my example I show you how to save the data as
JSON
and how to handle it when you retrieve it.My Solutions
I made a punker for you to play with till you get it done. You have to look at the Application tab in the dev tools when you inspect element. Then go to Storage. Then click on the run.plnkr.co storage link to see the counter saved to the localhost.
Link to Live Code
Please see the plunker here.
Make sure to look at the file
/src/app.ts
Eyes on Example
Code Example