如何使用本地存储在角度

我需要在浏览器的会话中存储数据,并在会话退出之前检索数据。如何在角度2中使用本地存储和会话存储?

349438 次浏览

使用 Angular2@LocalStorage模块,其描述如下:

这个小 Angular2/typecript 装饰器使得它非常容易保存 并在指令中自动恢复变量状态(类 属性)使用 HTML5’LocalStorage。

如果你需要使用 cookies,你应该看看: Https://www.npmjs.com/package/angular2-cookie

标准的 localStorageAPI应该是可用的,只要做例如:

localStorage.setItem('whatever', 'something');

得到了广泛的支持

注意,如果您还没有 "lib"数组,那么需要将 "dom"添加到 tsconfig.json中的 "lib"数组中。

如上所述,应该是: localStorageService.set('key', 'value');localStorageService.get('key');

如何从 localStorage 存储、检索和删除数据:

// General syntax for storing data
localStorage.setItem('key', 'value');
// Also note that both the key & the value has to be strings.
// So we stringify the value(if it's an object) before setting it.


// So, if you have an object that you want to save, stringify it like this


let data = {
'token': 'token',
'name': 'name'
};
localStorage.setItem('myLSkey', JSON.stringify(data));


// OR for individual key-value pairs
localStorage.setItem('myLSkey', JSON.stringify({
'token': 'token',
'name': 'name'
}));


// To retrieve the data & save it to an existing variable
data = JSON.parse(localStorage.getItem('myLSkey'));


// To remove a value/item from localStorage
localStorage.removeItem("myLSkey");

Tips : < br > You 也可以使用一个软件包为您的角度应用程序,这是基于 本地 localStorage API (我们在上面使用的)来实现这一点 您不必担心 stringify 和 parse,看看这个 角度5及以上的包装。 @ ngx-pwa/local-Storage < br > < br > 你也可以在谷歌上快速搜索“ maybe”,< strong > angle local Storage ,& find a package that has even more Github stars 等等

查看这个 呼叫了解更多关于 Web 存储 API 的信息。

我们可以很容易地使用 localStorage 来设置数据和接收数据。

注: 它同时适用于角2和角4

//set the data
localStorage.setItem(key, value);   //syntax example
localStorage.setItem('tokenKey', response.json().token);


//get the data
localStorage.getItem('tokenKey')


//confirm if token is exist or not
return localStorage.getItem('tokenKey') != null;

本地存储集项

句法:

  localStorage.setItem(key,value);
localStorage.getItem(key);

例如:

  localStorage.setItem("name","Muthu");
if(localStorage){   //it checks browser support local storage or not
let Name=localStorage.getItem("name");
if(Name!=null){  //  it checks values here or not to the variable
//do some stuff here...
}
}

你也可以用

    localStorage.setItem("name", JSON.stringify("Muthu"));

会话存储集项

句法:

  sessionStorage.setItem(key,value);
sessionStorage.getItem(key);

例如:

  sessionStorage.setItem("name","Muthu");


if(sessionStorage){ //it checks browser support session storage/not
let Name=sessionStorage.getItem("name");


if(Name!=null){  //  it checks values here or not to the variable
//do some stuff here...
}
}

你也可以用

   sessionStorage.setItem("name", JSON.stringify("Muthu"));

容易地存储和检索数据

保存到 LocalStorage:

localStorage.setItem('key', value);

对于具有属性的对象:

localStorage.setItem('key', JSON.stringify(object));

从本地仓库获取:

localStorage.getItem('key');

物品:

JSON.parse(localStorage.getItem('key'));

LocalStorage 对象将数据保存为 string 并检索为 string 如果 value 是以字符串形式存储的对象。 例如 parseInt(localStorage.getItem('key'));

最好使用框架提供的 localStroage,而不是第三方库 localStorageService 或其他任何东西,因为它减少了您的项目规模。

安装“角 -2-本地存储”

import { LocalStorageService } from 'angular-2-local-storage';

你可以使用 Cyrilletuzi 的 本地存储异步角2 + 服务

安装:

$ npm install --save @ngx-pwa/local-storage

用法:

// your.service.ts
import { LocalStorage } from '@ngx-pwa/local-storage';


@Injectable()
export class YourService {
constructor(private localStorage: LocalStorage) { }
}


// Syntax
this.localStorage
.setItem('user', { firstName:'Henri', lastName:'Bergson' })
.subscribe( () => {} );


this.localStorage
.getItem<User>('user')
.subscribe( (user) => { alert(user.firstName); /*should be 'Henri'*/ } );


this.localStorage
.removeItem('user')
.subscribe( () => {} );


// Simplified syntax
this.localStorage.setItemSubscribe('user', { firstName:'Henri', lastName:'Bergson' });
this.localStorage.removeItemSubscribe('user');

更多信息请点击:

Https://www.npmjs.com/package/@ngx-pwa/local-storage
Https://github.com/cyrilletuzi/angular-async-local-storage

下面是一个简单的服务示例,它使用 localStorage 来持久化数据:

import { Injectable } from '@angular/core';


@Injectable()
export class PersistanceService {
constructor() {}


set(key: string, data: any): void {
try {
localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
console.error('Error saving to localStorage', e);
}
}


get(key: string) {
try {
return JSON.parse(localStorage.getItem(key));
} catch (e) {
console.error('Error getting data from localStorage', e);
return null;
}
}
}

要使用这些服务,可以像平常一样在应用程序的某个模块中提供它,例如在 core 模块中。然后像这样使用:

import { Injectable } from '@angular/core';


@Injectable()
export class SomeOtherService {


constructor(private persister: PersistanceService) {}


someMethod() {
const myData = {foo: 'bar'};
persister.set('SOME_KEY', myData);
}


someOtherMethod() {
const myData = persister.get('SOME_KEY');
}
}

您也可以考虑使用我维护的库: < a href = “ https://github.com/zoomSphere/ngx-store”rel = “ norefrer”> ngx-store (npm i ngx-store)

它使得使用 localStorage、 sessionStorage 和 cookies 变得非常简单:

1) 设计师:

export class SomeComponent {
@LocalStorage() items: Array<string> = [];


addItem(item: string) {
this.items.push(item);
console.log('current items:', this.items);
// and that's all: parsing and saving is made by the lib in the background
}
}

装饰器存储的变量也可以在不同的类之间共享-还有为它设计的 @TempStorage()(别名为 @SharedStorage())装饰器。

2) 简单服务方法:

export class SomeComponent {
constructor(localStorageService: LocalStorageService) {}


public saveSettings(settings: SettingsInterface) {
this.localStorageService.set('settings', settings);
}


public clearStorage() {
this.localStorageService.utility
.forEach((value, key) => console.log('clearing ', key));
this.localStorageService.clear();
}
}

3) 构建器模式:

interface ModuleSettings {
viewType?: string;
notificationsCount: number;
displayName: string;
}


class ModuleService {
constructor(public localStorageService: LocalStorageService) {}


public get settings(): NgxResource<ModuleSettings> {
return this.localStorageService
.load(`userSettings`)
.setPath(`modules`)
.setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array
.appendPath(this.moduleId)
.setDefaultValue({});
}


public saveModuleSettings(settings: ModuleSettings) {
this.settings.save(settings);
}


public updateModuleSettings(settings: Partial<ModuleSettings>) {
this.settings.update(settings);
}
}

另一个重要的事情是您可以监听(每一个)存储更改,例如(下面的代码使用 RxJS v5语法) :

this.localStorageService.observe()
.filter(event => !event.isInternal)
.subscribe((event) => {
// events here are equal like would be in:
// window.addEventListener('storage', (event) => {});
// excluding sessionStorage events
// and event.type will be set to 'localStorage' (instead of 'storage')
});

WebStorageService.observe()返回一个常规的观察值,所以你可以压缩,过滤,反弹他们等。

我总是乐于听取建议和问题,帮助我改进这个库及其文档。

真正优雅的解决方案是修饰器。您可以使用它们来标记要存储的变量。

export class SomeComponent {


@LocalStorage
public variableToBeStored: string;


}

如何实现它的例子就在这篇文章(我的博客)

在本地存储中设置项或对象:

   localStorage.setItem('yourKey', 'yourValue');

若要在本地存储中获取项或对象,必须记住密钥。

   let yourVariable = localStorage.getItem('yourKey');

从本地存储中移除:

   localStorage.removeItem('yourKey');

Set item 的语法是

localStorage.setItem(key,value);

Get 项的语法是

localStorage.getItem(key);

这方面的一个例子是:

localStorage.setItem('email','abc@gmail.com');
let mail = localStorage.getItem("email");
if(mail){
console.log('your email id is', mail);
}
}

安装

npm install --save @ngx-pwa/local-storage

首先,你需要安装“角 -2-本地存储”

import { LocalStorageService } from 'angular-2-local-storage';

保存到 LocalStorage:

localStorage.setItem('key', value);

从本地仓库获取:

localStorage.getItem('key');

LocalStorage中存储:

window.localStorage.setItem(key, data);

LocalStorage中移除一个项目:

window.localStorage.removeItem(key);

LocalStorage获得一个项目:

window.localStorage.getItem(key);

只能在 LocalStorage中存储字符串; 如果有对象,首先必须像下面这样将其转换为字符串:

window.localStorage.setItem(key, JSON.stringify(obj));

当你想从 LocalStorage中得到一个物体时:

const result=JSON.parse(window.localStorage.getItem(key));

以上所有提示对于 SessionStorage都是一样的。

您可以使用以下服务处理 SessionStorageLocalStorage。该服务中的所有方法:

getSession(key: string): any
setSession(key: string, value: any): void
removeSession(key: string): void
removeAllSessions(): void
getLocal(key: string): any
setLocal(key: string, value: any): void
removeLocal(key: string): void
removeAllLocals(): void

在组件、服务和... 中注入此服务; 不要忘记在核心模块中注册该服务。

import { Injectable } from '@angular/core';


@Injectable()
export class BrowserStorageService {


getSession(key: string): any {
const data = window.sessionStorage.getItem(key);
if (data) {
return JSON.parse(data);
} else {
return null;
}
}


setSession(key: string, value: any): void {
const data = value === undefined ? '' : JSON.stringify(value);
window.sessionStorage.setItem(key, data);
}


removeSession(key: string): void {
window.sessionStorage.removeItem(key);
}


removeAllSessions(): void {
for (const key in window.sessionStorage) {
if (window.sessionStorage.hasOwnProperty(key)) {
this.removeSession(key);
}
}
}


getLocal(key: string): any {
const data = window.localStorage.getItem(key);
if (data) {
return JSON.parse(data);
} else {
return null;
}
}


setLocal(key: string, value: any): void {
const data = value === undefined ? '' : JSON.stringify(value);
window.localStorage.setItem(key, data);
}


removeLocal(key: string): void {
window.localStorage.removeItem(key);
}


removeAllLocals(): void {
for (const key in window.localStorage) {
if (window.localStorage.hasOwnProperty(key)) {
this.removeLocal(key);
}
}
}
}