Skip to content

Instantly share code, notes, and snippets.

@ajsaraujo
Created October 26, 2022 12:41
Show Gist options
  • Save ajsaraujo/9ade92bf4f84025859bc68fd658983e9 to your computer and use it in GitHub Desktop.
Save ajsaraujo/9ade92bf4f84025859bc68fd658983e9 to your computer and use it in GitHub Desktop.
Preferences Service
import { Injectable } from '@angular/core';
import { LocalStorage } from '../storage/local.storage';
interface Preferences {
myPreference: string;
}
@Injectable({ providedIn: 'root' })
export class PreferencesService {
preferences: Preferences;
private readonly LOCAL_STORAGE_KEY = 'preferences';
constructor(private localStorage: LocalStorage) {
const DEFAULT_PREFERENCES: Preferences = {
myPreference: 'foo',
};
const storedPreferences = this.readFromLocalStorage();
this.preferences = {
...DEFAULT_PREFERENCES,
...storedPreferences,
};
}
update(preferences: Partial<Preferences>) {
Object.assign(this.preferences, preferences);
this.saveToLocalStorage();
}
set(preference: keyof Preferences, value: any) {
this.preferences[preference] = value;
this.saveToLocalStorage();
}
get(preference: keyof Preferences) {
return this.preferences[preference];
}
private saveToLocalStorage() {
const stringifiedPreferences = JSON.stringify(this.preferences);
this.localStorage.setItem(this.LOCAL_STORAGE_KEY, stringifiedPreferences);
}
private readFromLocalStorage() {
const stringifiedPreferences = this.localStorage.getItem(
this.LOCAL_STORAGE_KEY
);
return JSON.parse(stringifiedPreferences);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment