Last active
June 7, 2020 10:55
-
-
Save Dornhoth/a9e3d5e7305cdc2aa76b336cc1e5cd4e to your computer and use it in GitHub Desktop.
Persistence Service with Injection Token for Storage
This file contains hidden or 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, InjectionToken, Inject } from '@angular/core'; | |
export const STORAGE = new InjectionToken<Storage>('Storage', { | |
providedIn: 'root', | |
factory: () => localStorage | |
}); | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class PersistenceService { | |
constructor(@Inject(STORAGE) public storage: Storage) {} | |
set(key: string, data: any): void { | |
this.storage.setItem(key, JSON.stringify(data)); | |
} | |
get(key: string): any { | |
return JSON.parse(this.storage.getItem(key)); | |
} | |
remove(key: string): void { | |
this.storage.removeItem(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment