1// localStorage for objects, arrays or any data type
2var obj = {
3 firstName: "Bob",
4 lastName: "Jeff",
5 age: 13
6}
7localStorage.setItem("itemname", JSON.stringify(obj)); // Save the obj as string
8var item = JSON.parse(localStorage.getItem("itemname"));
9// ^^ Parse string then set `item` as the obj
1window.localStorage.setItem('myCat', 'Tom');
2const cat = window.localStorage.getItem('myCat');
1localStorage.setItem('name', 'Bob') // make/set a key/value
2var username = localStorage.getItem('name') // get the key
3console.log(username) // log the key
4// This data will be saved even after you close the page
1localStorage.setItem('Items' , 'Bread');
2let Bread = localStorage.getItem('Items');
1// using in HTML5 (frontend)
2
3// set
4localStorage.setItem('users', 'vilh');
5
6users = [
7 {
8 id: 1,
9 name: 'vilh',
10 },
11 {
12 id: 2,
13 name: 'zidane'
14 },
15]
16
17// set string
18localStorage.setItem('users', users); // stored objects
19localStorage.setItem('users', JSON.stringify(users)); // stored string
20
21// get
22var retrievedUsername = localStorage.getItem('users');
1 import { Injectable, OnDestroy } from '@angular/core';
2 import { Subject } from 'rxjs/Subject';
3 import { share } from 'rxjs/operators';
4
5 @Injectable()
6 export class StorageService implements OnDestroy {
7 private onSubject = new Subject<{ key: string, value: any }>();
8 public changes = this.onSubject.asObservable().pipe(share());
9
10 constructor() {
11 this.start();
12 }
13
14 ngOnDestroy() {
15 this.stop();
16 }
17
18 public getStorage() {
19 let s = [];
20 for (let i = 0; i < localStorage.length; i++) {
21 s.push({
22 key: localStorage.key(i),
23 value: JSON.parse(localStorage.getItem(localStorage.key(i)))
24 });
25 }
26 return s;
27 }
28
29 public store(key: string, data: any): void {
30 localStorage.setItem(key, JSON.stringify(data));
31 this.onSubject.next({ key: key, value: data})
32 }
33
34 public clear(key) {
35 localStorage.removeItem(key);
36 this.onSubject.next({ key: key, value: null });
37 }
38
39
40 private start(): void {
41 window.addEventListener("storage", this.storageEventListener.bind(this));
42 }
43
44 private storageEventListener(event: StorageEvent) {
45 if (event.storageArea == localStorage) {
46 let v;
47 try { v = JSON.parse(event.newValue); }
48 catch (e) { v = event.newValue; }
49 this.onSubject.next({ key: event.key, value: v });
50 }
51 }
52
53 private stop(): void {
54 window.removeEventListener("storage", this.storageEventListener.bind(this));
55 this.onSubject.complete();
56 }
57 }
58