gpt4 book ai didi

javascript - HTML5 本地存储 Angular 2

转载 作者:太空狗 更新时间:2023-10-29 18:06:51 25 4
gpt4 key购买 nike

我现在第一次尝试在 Angular2 中实现本地存储,但有点困惑。

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

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

这是我在 FormComponent 中使用的类

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

我绑定(bind)它,表单中的所有内容都很好用。现在我想将它存储在本地存储中(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 = ;
*/
}


}

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

最佳答案

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

Use the localStorage.setItem(key, value); method where you want to set the data.

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

.. and localStorage.getItem(key); where you want to get the data.

myTestFunction() {

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

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

LOCAL STORAGE UTILITY CLASS

关于javascript - HTML5 本地存储 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45673269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com