How to store an object (of a class type) in browse

2019-01-29 12:42发布

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

3条回答
Fickle 薄情
2楼-- · 2019-01-29 12:56

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

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-29 13:00

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!

查看更多
萌系小妹纸
4楼-- · 2019-01-29 13:14

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

enter image description here

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()
}
查看更多
登录 后发表回答