To store in LocalStorage
:
window.localStorage.setItem(key, data);
To remove an item from LocalStorage
:
window.localStorage.removeItem(key);
To get an item from LocalStorage
:
window.localStorage.getItem(key);
You can only store a string in LocalStorage
; if you have an object, first you have to convert it to string like the following:
window.localStorage.setItem(key, JSON.stringify(obj));
And when you want to get an object from LocalStorage
:
const result=JSON.parse(window.localStorage.getItem(key));
All Tips above are the same for SessionStorage
.
You can use the following service to work on SessionStorage
and LocalStorage
. All methods in the service :
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
Inject this service in your components, services and ...; Do not forget to register the service in your core module.
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);
}
}
}
}