2 * Store and retrieve data from various sources.
5 * 1. LocalItem: Stored in window.localStorage and persist indefinitely.
6 * 2. SessionItem: Stored in window.sessionStorage and persist until
7 * the end of the current browser tab/window. Data is only available
8 * to the tab/window where the data was set.
9 * 3. LoginItem: Stored as session cookies and persist until the browser
10 * is closed. These values are avalable to all browser windows/tabs.
12 import {Injectable} from '@angular/core';
13 import {CookieService} from 'ngx-cookie';
15 @Injectable({providedIn: 'root'})
16 export class StoreService {
18 // Base path for cookie-based storage.
19 // Useful for limiting cookies to subsections of the application.
20 // Store cookies globally by default.
21 // Note cookies shared with /eg/staff must be stored at "/"
22 loginSessionBasePath = '/';
24 // Set of keys whose values should disappear at logout.
25 loginSessionKeys: string[] = [
33 private cookieService: CookieService) {
36 private parseJson(valJson: string): any {
37 if (valJson === undefined || valJson === null || valJson === '') {
41 return JSON.parse(valJson);
43 console.error(`Failure to parse JSON: ${E} => ${valJson}`);
49 * Add a an app-local login session key
51 addLoginSessionKey(key: string): void {
52 this.loginSessionKeys.push(key);
55 setLocalItem(key: string, val: any, isJson?: boolean): void {
57 val = JSON.stringify(val);
59 window.localStorage.setItem(key, val);
62 setSessionItem(key: string, val: any, isJson?: boolean): void {
64 val = JSON.stringify(val);
66 window.sessionStorage.setItem(key, val);
69 setLoginSessionItem(key: string, val: any, isJson?: boolean): void {
71 val = JSON.stringify(val);
73 this.cookieService.put(key, val,
74 {path : this.loginSessionBasePath, secure: true});
77 getLocalItem(key: string): any {
78 return this.parseJson(window.localStorage.getItem(key));
81 getSessionItem(key: string): any {
82 return this.parseJson(window.sessionStorage.getItem(key));
85 getLoginSessionItem(key: string): any {
86 return this.parseJson(this.cookieService.get(key));
89 removeLocalItem(key: string): void {
90 window.localStorage.removeItem(key);
93 removeSessionItem(key: string): void {
94 window.sessionStorage.removeItem(key);
97 removeLoginSessionItem(key: string): void {
98 this.cookieService.remove(key, {path : this.loginSessionBasePath});
101 clearLoginSessionItems(): void {
102 this.loginSessionKeys.forEach(
103 key => this.removeLoginSessionItem(key)