繁体   English   中英

HTML5本地存储Angular 2

[英]HTML5 local storage Angular 2

我尝试首次在Angular2中实现一个本地存储,并且有点困惑。

所以,我有第一个组件,我注册我的用户

export class FormComponent {
  modus = ['first', 'second'];
  model: User = new User('', '', '');
  constructor(private _cookieService: CookieService) {}
}

这是我在FormComponent使用的FormComponent

export class User {
  constructor (
    public email: string,
    public name: string,
    public modus: string
  ) {}
}

我绑定它,形式上的一切都很好。 现在我想将它存储在本地存储中( User 3个参数)

但我怎么能这样做?

我离开这个页面注册用户并转到其他页面,如

export class Part1Component {
  public email;
  public name;
  public modus;

  constructor(private _location: Location) {}
     myTestFunction(){

    /* assign values here
       this.email = ;
       this.name = ;
       this.modus = ;
   */
       }


 }

我如何从存储中获取值并在此处分配它们?

如果使用JSON.stringify()在会话存储中存储用户对象,则可以执行此操作

let user = JSON.parse(localStorage.getItem('user'));
this.email=user.email;
this.name=user.name;

Typescript提供了localStorage ,您可以使用它来设置和获取存储数据。

使用localStorage.setItem(key, value); 要设置数据的方法。

localStorage.setItem('__user__email', user.email);
localStorage.setItem('__user__name', user.name);
localStorage.setItem('__user__modus', user.modus);

..和localStorage.getItem(key); 你想要获取数据的地方。

myTestFunction() {

    // assign values here
    this.email = localStorage.getItem('__user__email');
    this.name  = localStorage.getItem('__user__name');
    this.modus = localStorage.getItem('__user__modus');
}

您可以查看此实用程序类并使用我在其中一个项目中创建的实用程序类:

本地存储实用程序类

您应该使用localStorage.setItem()来保存数据,使用localStorage.getItem()来从localStorage获取您保存的数据。 有关更多详细信息,请阅读本地存储文档

以下是使用localStorage的简单示例。

将数据保存到localStorage:

localStorage.setItem('userKey', JSON.stringify(this.model));

请注意,您只能将字符串保存到localStorage。

从localStorage获取保存的数据作为示例:

let savedUser: User = JSON.parse(localStorage.getItem('userKey'));

如果要清除或删除已保存的数据,可以使用以下代码:

localStorage.removeItem('userKey');

要么

localStorage.clear();

您可以在应用程序中将每个点的数据请求到localStorage。

像这样使用html5 localStorage

localStorage.setItem(“key”,value)设置一个项目,然后即使你关闭了borwser你也可以得到它。

localStorage.getItem( “钥匙”);

并保存为字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM