Created
July 15, 2022 18:32
-
-
Save riscie/5600dead9465c1f0126344cc114fa7b0 to your computer and use it in GitHub Desktop.
Generic Angular Typescript Localstorage Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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