Skip to content

Instantly share code, notes, and snippets.

@Dornhoth
Last active June 7, 2020 10:55
Show Gist options
  • Save Dornhoth/a9e3d5e7305cdc2aa76b336cc1e5cd4e to your computer and use it in GitHub Desktop.
Save Dornhoth/a9e3d5e7305cdc2aa76b336cc1e5cd4e to your computer and use it in GitHub Desktop.
Persistence Service with Injection Token for Storage
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