Skip to content

Instantly share code, notes, and snippets.

@riscie
Created July 15, 2022 18:32
Show Gist options
  • Save riscie/5600dead9465c1f0126344cc114fa7b0 to your computer and use it in GitHub Desktop.
Save riscie/5600dead9465c1f0126344cc114fa7b0 to your computer and use it in GitHub Desktop.
Generic Angular Typescript Localstorage Service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class LocalstorageService {
constructor() {}
set(key: string, value: any) {
localStorage.setItem(key, JSON.stringify(value));
}
get<T>(key: string): T | null {
const itemJsonString = localStorage.getItem(key);
if (itemJsonString === null) {
return null;
}
try {
return JSON.parse(itemJsonString) as T;
} catch (e) {
return null;
}
}
remove(key: string) {
localStorage.removeItem(key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment