Angular Data Persistence: Remembering User Preferences
In modern web applications, it's common to want to save user preferences or application state so that they persist across sessions. This challenge focuses on implementing a simple persistence mechanism in an Angular application using localStorage.
Problem Description
Your task is to create an Angular service that allows a component to save and retrieve a user's preferred theme (e.g., 'light' or 'dark') using the browser's localStorage. The service should handle the serialization and deserialization of data and gracefully manage cases where no preference has been saved yet.
Key Requirements:
- Persistence Service: Create a new Angular service (e.g.,
PersistenceService) responsible for interacting withlocalStorage. - Save Preference: Implement a method in the service to save the user's theme preference to
localStorage. - Load Preference: Implement a method to retrieve the user's theme preference from
localStorage. If no preference is found, it should return a default value. - Clear Preference: Implement a method to remove the theme preference from
localStorage. - Data Format: Store the preference as a string.
- Component Integration: Demonstrate how a component can utilize this service to manage its theme.
Expected Behavior:
- When the application starts, if a theme is saved in
localStorage, it should be loaded and applied. - If no theme is saved, a default theme should be used.
- When the user changes their theme (e.g., via a button click in the component), the new preference should be saved to
localStorage. - Refreshing the page should retain the last selected theme.
Edge Cases:
- What happens if
localStorageis unavailable or disabled? - What happens if the data in
localStorageis corrupted (though for this simple string value, this is less likely)?
Examples
Example 1: Initial Load with No Saved Preference
Component State (before interacting with service):
themePreference: string = 'light' (default)
Action:
A component calls persistenceService.loadThemePreference(). localStorage is empty for the theme key.
Output from loadThemePreference():
'light'
Explanation:
Since localStorage doesn't contain a saved theme, the service returns the predefined default value.
Example 2: Saving and Loading a Preference
Component State:
themePreference: string = 'light'
Action 1:
User clicks a button to change theme to 'dark'. The component calls persistenceService.saveThemePreference('dark').
localStorage now contains: {'userTheme': 'dark'}
Action 2:
Component then calls persistenceService.loadThemePreference().
Output from loadThemePreference():
'dark'
Explanation:
The saveThemePreference method successfully wrote 'dark' to localStorage under the key 'userTheme'. The loadThemePreference method then retrieved this value.
Example 3: Clearing a Preference
Component State:
themePreference: string = 'dark'
Action:
User clicks a button to reset their preference. The component calls persistenceService.clearThemePreference().
localStorage is now empty for the theme key.
Next Action:
If the component then calls persistenceService.loadThemePreference().
Output from loadThemePreference():
'light' (assuming 'light' is the default)
Explanation:
clearThemePreference removed the 'userTheme' entry from localStorage. A subsequent load defaults back to the initial setting.
Constraints
- The persistence key used in
localStorageshould be a consistent string (e.g.,'userTheme'). - The service methods should return promises or Observables to allow for asynchronous operations and error handling, especially if
localStorageoperations could potentially fail (though directlocalStorageis synchronous in browsers). For this challenge, returning plain values is acceptable iflocalStorageis assumed to be available. - The component should demonstrate basic usage of the service.
Notes
- Consider how you would handle potential errors during
localStorageaccess (e.g., iflocalStorageis full or disabled). A simple approach for this challenge is to assumelocalStorageis available and functional. - For more complex data, you would need to consider JSON stringification and parsing.
- Think about where the default theme value should be defined – within the service, or passed in? For this challenge, defining it within the service is acceptable.
- This challenge focuses on the service implementation. You'll need to create a basic Angular component to showcase its usage.
- You can use
localStorage.setItem(key, value)to save andlocalStorage.getItem(key)to retrieve, andlocalStorage.removeItem(key)to clear.