Skip to content

Instantly share code, notes, and snippets.

@navix
Last active April 11, 2024 09:04
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navix/f47902a8b49a4d7c18ff8a50077d949e to your computer and use it in GitHub Desktop.
Save navix/f47902a8b49a4d7c18ff8a50077d949e to your computer and use it in GitHub Desktop.
Angular LocalStorage/SessionStorage services. Universal (SSR) compatible.
import { Platform } from '@angular/cdk/platform';
import { Injectable } from '@angular/core';
import { MemoryStorage } from './memory-storage';
@Injectable({
providedIn: 'root',
})
export class LocalStorage implements Storage {
private readonly storage: Storage;
constructor(private _platform: Platform) {
if (this._platform.isBrowser && window?.localStorage) {
this.storage = window.localStorage;
} else {
this.storage = new MemoryStorage();
}
}
get length(): number {
return this.storage.length;
}
clear(): void {
this.storage.clear();
}
getItem(key: string): string | null {
return this.storage.getItem(key);
}
key(index: number): string | null {
return this.storage.key(index);
}
removeItem(key: string): void {
this.storage.removeItem(key);
}
setItem(key: string, value: string): void {
this.storage.setItem(key, value);
}
}
import { Injectable } from '@angular/core';
@Injectable()
export class MemoryStorage implements Storage {
private data: { [key: string]: string } = {};
get length(): number {
return Object.keys(this.data).length;
}
clear(): void {
this.data = {};
}
getItem(key: string): string | null {
return key in this.data ? this.data[key] : null;
}
key(index: number): string | null {
const keys = Object.keys(this.data);
return index >= 0 && keys.length < index ? keys[index] : null;
}
removeItem(key: string): void {
delete this.data[key];
}
setItem(key: string, value: string): void {
this.data[key] = value;
}
}
import { Platform } from '@angular/cdk/platform';
import { Injectable } from '@angular/core';
import { MemoryStorage } from './memory-storage';
@Injectable({
providedIn: 'root',
})
export class SessionStorage implements Storage {
private readonly storage: Storage;
constructor(private _platform: Platform) {
if (this._platform.isBrowser && window?.sessionStorage) {
this.storage = window.sessionStorage;
} else {
this.storage = new MemoryStorage();
}
}
get length(): number {
return this.storage.length;
}
clear(): void {
this.storage.clear();
}
getItem(key: string): string | null {
return this.storage.getItem(key);
}
key(index: number): string | null {
return this.storage.key(index);
}
removeItem(key: string): void {
this.storage.removeItem(key);
}
setItem(key: string, value: string): void {
this.storage.setItem(key, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment