Javascript Angular 2中的本地存储
我需要在浏览器的会话中存储数据,并在会话退出之前检索数据。如何在Angular 2中使用本地和会话存储?使用模块,其描述如下: 这个小小的Angular2/typescript装饰器使保存变得超级容易 并自动恢复指令(类)中的变量状态 属性)使用HTML5的LocalStorage 如果您需要使用cookies,请查看: 标准应可用,只需执行以下操作:Javascript Angular 2中的本地存储,javascript,angular,local-storage,session-variables,Javascript,Angular,Local Storage,Session Variables,我需要在浏览器的会话中存储数据,并在会话退出之前检索数据。如何在Angular 2中使用本地和会话存储?使用模块,其描述如下: 这个小小的Angular2/typescript装饰器使保存变得超级容易 并自动恢复指令(类)中的变量状态 属性)使用HTML5的LocalStorage 如果您需要使用cookies,请查看: 标准应可用,只需执行以下操作: localStorage.setItem('whatever', 'something'); 是的 请注意,如果您还没有tsconfig.js
localStorage.setItem('whatever', 'something');
是的
请注意,如果您还没有
tsconfig.json
,则需要将“dom”
添加到“lib”
数组中 如上所述,应该是:localStorageService.set('key','value')
和localStorageService.get('key')代码>如何从本地存储中存储、检索和删除数据:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
快速提示:
您也可以使用基于
本机本地存储API(我们在上面使用)来实现这一点,以及
您不必担心字符串化和解析。看看这个
角度5及以上的包装
你也可以在谷歌上快速搜索,angular local
存储,&查找包含更多Github stars等的软件包
查看此链接以了解有关Web存储API的更多信息。我们可以轻松使用localStorage设置数据和接收数据
注意:它同时适用于angular2和Angular4
//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;
本地存储集项
语法:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
示例:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
你也可以使用
localStorage.setItem("name", JSON.stringify("Muthu"));
sessionStorage.setItem("name", JSON.stringify("Muthu"));
会话存储集项
语法:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
示例:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
你也可以使用
localStorage.setItem("name", JSON.stringify("Muthu"));
sessionStorage.setItem("name", JSON.stringify("Muthu"));
轻松存储和检索数据保存到本地存储:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
对于具有属性的对象:
localStorage.setItem('key', JSON.stringify(object));
从本地存储获取:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
对于对象:
JSON.parse(localStorage.getItem('key'));
localStorage对象将数据另存为字符串并检索为字符串。您需要解析所需的输出
如果值是存储为字符串的对象。
e、 g.parseInt(localStorage.getItem('key'))代码>
最好使用框架提供的localStroage,而不是第三方库localStorageService或其他任何东西,因为这样可以减少项目规模。安装“angular-2-local-storage”
您可以使用cyrilletuzi的LocalStorage 2+服务
安装:
$npm安装--保存@ngx pwa/本地存储
用法:
//your.service.ts
从'@ngx pwa/local storage'导入{LocalStorage};
@可注射()
出口类服务{
构造函数(私有localStorage:localStorage){}
}
//语法
这是本地存储
.setItem('user',{firstName:'Henri',lastName:'Bergson'})
.subscribe(()=>{});
这是本地存储
.getItem('用户')
.subscribe((user)=>{alert(user.firstName);/*应为'Henri'*/});
这是本地存储
.removeItem(“用户”)
.subscribe(()=>{});
//简化语法
this.localStorage.setItemSubscribe('user',{firstName:'Henri',lastName:'Bergson'});
this.localStorage.removietemsubscribe('user');
更多信息请点击此处:
下面是一个简单服务的示例,它使用本地存储来持久化数据:
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;
}
}
}
要使用此服务,请在应用程序中的某些模块(如普通模块)中提供,例如在核心模块中。然后像这样使用:
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');
}
}
您也可以考虑使用我维护的库:<强> < /强>(<代码> NPM I NGX存储< /COD>)
它使使用本地存储、会话存储和cookie变得非常简单。有几种受支持的方法可以操作数据:
1) 装饰师:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
3) 构建器模式:
// 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 as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));
// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));
// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));
// To remove a value/item from localStorage
localStorage.removeItem("some-key");
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...
}
}
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...
}
}
localStorage.setItem('key', value);
localStorage.getItem('key');
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
}
}
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();
}
}
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);
}
}
WebStorageService.observe()
返回一个常规的可观察对象,因此您可以对其进行压缩、过滤和跳出等操作
我总是乐于听取帮助我改进此库及其文档的建议和问题。真正优雅的解决方案是装饰师。您可以使用它们来标记要存储的变量
export class SomeComponent {
@LocalStorage
public variableToBeStored: string;
}
要在本地存储器中设置项目或对象,请执行以下操作:
localStorage.setItem('yourKey', 'yourValue');
localStorage.removeItem('yourKey');
要在本地存储中获取项目或对象,必须记住密钥
let yourVariable = localStorage.getItem('yourKey');
要将其从本地存储中删除,请执行以下操作:
localStorage.setItem('yourKey', 'yourValue');
localStorage.removeItem('yourKey');
set项的语法为
localStorage.setItem(key,value);
get item的语法是
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
首先,您需要安装“angular-2-local-storage”
保存到本地存储:
localStorage.setItem('key', value);
从本地存储获取:
localStorage.getItem('key');
要存储在本地存储中
:
window.localStorage.setItem(key, data);
window.localStorage.removeItem(key);
window.localStorage.getItem(key);
const result=JSON.parse(window.localStorage.getItem(key));
要从LocalStorage
中删除项目,请执行以下操作:
window.localStorage.setItem(key, data);
window.localStorage.removeItem(key);
window.localStorage.getItem(key);
const result=JSON.parse(window.localStorage.getItem(key));
要从LocalStorage
获取项目,请执行以下操作:
window.localStorage.setItem(key, data);
window.localStorage.removeItem(key);
window.localStorage.getItem(key);
const result=JSON.parse(window.localStorage.getItem(key));
只能在LocalStorage
中存储字符串;如果有对象,首先必须将其转换为字符串,如下所示:
window.localStorage.setItem(key, JSON.stringify(obj));
当您想从LocalStorage
获取对象时:
window.localStorage.setItem(key, data);
window.localStorage.removeItem(key);
window.localStorage.getItem(key);
const result=JSON.parse(window.localStorage.getItem(key));
以上所有提示对于会话存储都是相同的
您可以使用以下服务处理会话存储
和本地存储
。服务中的所有方法:
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);
}
}
}
}
打字稿很适合我。你有没有找到一种方法来解决这个问题,而不必使用其他答案中列出的npm?@Winnemucca“投掷适合”不是一个有用的问题陈述。我不记得添加了超出Angular CLI包括的任何内容。我道歉。我必须进入我的ts.config文件来修复它。“lib”:[“es2016”,“dom”]。您已经添加了“dom”吗?@Winnemucca是的,这是由CLI设置的。我已经将它添加到了答案中。localStorage.getItem('key');setItem('key','value');目前没有人维护它。angular2 cookie项目的继任者是ngx cookie t