如何在浏览器的存储中存储对象(类类型)并检索它?

时间:2017-03-05 01:14:27

标签: javascript angular local-storage

我希望在Angular 2应用程序中有一个页面重新加载证明类实例。

在我的组件的.ts文件中,我有类:

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()
}

我知道localStorage ES6的东西可以存储字符串。我是否必须编写自己的复杂类对象的反序列化? 喜欢(我认为)建议:Angular 2 map http response to instance of class

3 个答案:

答案 0 :(得分:1)

我建议使用angular-2-local-storage node_module。

步骤:

  1. 安装npm install angular-2-local-storage
  2. 确保将包添加到config.js(systemjs或webpack)
  3. 导入模块和服务,如下所示

    import { LocalStorageModule,LocalStorageService} from 'angular-2-local-storage';
    
  4. 将模块添加到导入数组并将服务添加到providers数组中

     imports: [ BrowserModule,
       LocalStorageModule.withConfig({storageType: 'localStorage'}), ],
    
     providers:[LocalStorageService],
    
  5. 将服务作为依赖项注入组件,如下所示

    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')
    }
    
  6. <强> LIVE DEMO

答案 1 :(得分:1)

使用import sys import os import numpy import matplotlib.pyplot as plt from pylab import * trap_error = 'mag_velocity.txt' mag, vel = numpy.loadtxt(trap_error, unpack =True) #plt.plot(vel, mag, '\\bigoplus') plt.plot(vel, mag, marker='$\\bigoplus$', markersize=15) plt.ylim(-11, -19) plt.xlim(-2, -7) plt.show() 即可:

localStorage

使用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) } } ,您可以存储任何您想要的复杂对象。

希望这有帮助!

答案 2 :(得分:1)

您的问题

我不明白你在试图用柜台做什么。因此,我继续为您提供了一个操作计数器的方法的简单示例,并将其保存到localStorage

在我的示例中,我将向您展示如何将数据保存为JSON以及如何在检索数据时将其处理。

我的解决方案

我为你玩了一个玩家,直到你完成它。检查元素时,您必须查看开发工具中的“应用程序”选项卡。然后去存储。然后单击run.plnkr.co存储链接以查看保存到localhost的计数器。

链接到实时代码

Please see the plunker here.

请务必查看文件/src/app.ts

关注示例

enter image description here

代码示例

//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()
}