Skip to content

Instantly share code, notes, and snippets.

@leon
Created February 25, 2017 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leon/723840170f86263256f487d5453309ae to your computer and use it in GitHub Desktop.
Save leon/723840170f86263256f487d5453309ae to your computer and use it in GitHub Desktop.
Angular LocalStorageService
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