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

前端 未结 3 2328
生来不讨喜
生来不讨喜 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:14

    I would suggest with angular-2-local-storage node_module.

    Steps:

    1. Install npm install angular-2-local-storage
    2. Make sure that the package is added in the config.js(systemjs or webpack)
    3. Import the module and service as below

      import { LocalStorageModule,LocalStorageService} from 'angular-2-local-storage';
      
    4. Add the module to imports array and service to providers array as

       imports: [ BrowserModule,
         LocalStorageModule.withConfig({storageType: 'localStorage'}), ],
      
       providers:[LocalStorageService],
      
    5. Inject the Service as a dependency into component as below

      constructor(private localStorageService: LocalStorageService) {
              this.name = 'Angular-2-Local-Storage-Demo';
              this.localStorageService.add('a',this.user);
              console.log(this.localStorageService.get('a')); 
              this.valuFromLocalStorage= this.localStorageService.get('a')
      }
      

    LIVE DEMO

    0 讨论(0)
  • 2020-12-22 10:26

    using localStorage you can do this:

    import { Component, OnInit } from '@angular/core';
    class Bar {
       baz: number = 11;
    }
    class Foo {
       bar: Bar = new Bar()
    }
    @Component({
      selector: 'a-component',
      template: `<br><button (click)='reset()'>Reset</button>`
    })
    export class AComponent implements OnInit{ 
      foo: Foo = new Foo();
      constructor(){
           this.incrementBaz()
      }
      ngOnInit(): void {
        this.foo = JSON.parse(localStorage.getItem('foo'))
        console.log('baz=', this.foo.bar.baz)
      }
      incrementBaz() {
        let old = JSON.parse(localStorage.getItem('foo'))
        if (old) {
            old.bar.baz += 1;
            localStorage.setItem('foo', JSON.stringify(old))    
        }
        else {
            localStorage.setItem('foo', JSON.stringify(this.foo))
        }
      }
      reset() {
        this.foo = new Foo();
        localStorage.setItem('foo', JSON.stringify(this.foo))
        console.log('baz=', this.foo.bar.baz)
      }
    }
    

    with localStorage you can store whatever complex object you want.

    hope this helps!

    0 讨论(0)
  • 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: `
        <div>
          <h2>Hello {{name}}</h2>
        </div>
      `,
    })
    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()
    }
    
    0 讨论(0)
提交回复
热议问题