Created
February 25, 2017 16:22
-
-
Save leon/723840170f86263256f487d5453309ae to your computer and use it in GitHub Desktop.
Angular LocalStorageService
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() | |
export class LocalStorageService { | |
public localStorage: any; | |
constructor() { | |
if (!localStorage) { | |
throw new Error('Current browser does not support Local Storage'); | |
} | |
this.localStorage = localStorage; | |
} | |
public set(key: string, value: string): void { | |
this.localStorage[key] = value; | |
} | |
public get(key: string): string { | |
return this.localStorage[key]; | |
} | |
public setObject(key: string, value: any): void { | |
this.localStorage[key] = JSON.stringify(value); | |
} | |
public getObject(key: string): any { | |
const val = this.localStorage[key]; | |
if (!val) { | |
return undefined; | |
} | |
return JSON.parse(val); | |
} | |
public remove(key: string): any { | |
this.localStorage.removeItem(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment