How to store an object (of a class type) in browser's storage and retrieve it?

前端 未结 3 2350
生来不讨喜
生来不讨喜 2020-12-22 09:47

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 i         


        
3条回答
  •  执念已碎
    2020-12-22 10:30

    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

    //our root app component
    import {Component, NgModule, OnInit} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    
    @Component({
      selector: 'my-app',
      template: `
        

    Hello {{name}}

    `, }) export class App { foo: Foo = new Foo(); ngOnInit() { // This will always be 12, it would be nice if it would increase with each page refresh. var counter = JSON.parse(localStorage.getItem('counter')); var tick = this.foo.bar.baz + counter + 1; localStorage.setItem('counter', JSON.stringify(tick)); console.log('this is my tick ' + tick); } } @NgModule({ imports: [ BrowserModule ], declarations: [ App ], bootstrap: [ App ] }) export class AppModule {} class Bar { baz: number = 11; } class Foo { bar: Bar = new Bar() }

提交回复
热议问题