38 lines
764 B
TypeScript
38 lines
764 B
TypeScript
import { Injectable } from "@angular/core";
|
|
|
|
@Injectable({
|
|
providedIn: "root",
|
|
})
|
|
export class SessionStorageService {
|
|
setItem<T>(key: string, value: T) {
|
|
try {
|
|
const item = JSON.stringify(value);
|
|
sessionStorage.setItem(key, item);
|
|
} catch (e) {
|
|
console.error("Could not set item", e);
|
|
}
|
|
}
|
|
|
|
getItem<T>(key: string): T | null {
|
|
try {
|
|
const item = sessionStorage.getItem(key);
|
|
return item ? (JSON.parse(item) as T) : null;
|
|
} catch (e) {
|
|
console.error("Could not get item", e);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @throws Error if key is not found.
|
|
* @param key
|
|
*/
|
|
removeItem(key: string): void {
|
|
sessionStorage.removeItem(key);
|
|
}
|
|
|
|
clear(): void {
|
|
sessionStorage.clear();
|
|
}
|
|
}
|