Managing data between page reloads and user interactions is a common challenge. One powerful solution to this problem is the use of browser storage mechanisms like session storage. However, working with session storage can be a complex task, especially when it involves handling different types of data.
By creating a generic session storage handler service, we can standardize access to the browser API’s for session storage and thus manage the session data more consistently
Let’s start by running the cli command to generate a service for us. This service will act as a container for our session storage implementation and all its utility functions.
ng generate service sessionStorage
Once our service is created lets add some of these utility functions and methods to store data into session storage via the browser session storage API.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SessionStorageService {
constructor() { }
getItem(key: string) {
try {
const result = JSON.parse(sessionStorage.getItem(key) || '{}');
return result;
} catch (error: any) {
console.log(error);
}
}
setItem(key: string, value: string | any) {
try {
return sessionStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.log(error);
}
}
removeItem(key: string) {
try {
return sessionStorage.removeItem(key);
} catch (error) {
console.log(error);
}
}
clearEntireSession() {
sessionStorage.clear();
}
}
getItem(key: string)
: Retrieves data from sessionStorage
based on the provided key and returns it in a structured format. If there’s an error parsing the data, it logs the error to the console.setItem(key: string, value: string | any)
: Stores data in sessionStorage
under the specified key. It serializes the data to JSON format before storage. If an error occurs during storage, it logs the error.removeItem(key: string)
: Removes data from sessionStorage
based on the provided key. If an error occurs during removal, it logs the error.clearEntireSession()
: Clears the entire sessionStorage
, effectively removing all stored data. This function is useful when you want to reset or clear all network request and response datasetItem
to store their authentication token or user object in sessionStorage
. When the user logs out, you can call removeItem
to clear the stored authentication data.
// When user logs in const user = { id: 123, username: 'example_user' }; sessionStorageService.setItem('user', user); // When user logs out sessionStorageService.removeItem('user');
sessionStorage
to store the user’s cart items temporarily. This way, the cart items will persist across page reloads until the user completes the purchase or logs out.
// Add item to the cart
const cartItem = { productId: 456, quantity: 2 };
const currentCart = sessionStorageService.getItem('cart') || []; currentCart.push(cartItem); sessionStorageService.setItem('cart', currentCart);
// Retrieve and display the cart
const userCart = sessionStorageService.getItem('cart');
sessionStorage
to store the form data temporarily. This way, you can retrieve and populate the form with the saved data when the user returns.
// Save form data const formData = { name: 'John', email: 'john@example.com' }; sessionStorageService.setItem('formData', formData); // Retrieve and populate the form const savedFormData = sessionStorageService.getItem('formData');
sessionStorage
for later analysis.
try { // Code that may throw an error }
catch (error) {
const errorDetails = { message: error.message, stack: error.stack, timestamp: new Date().toISOString(), }; sessionStorageService.setItem('errorLog', errorDetails); }
// Retrieve and review error logs
const errorLog = sessionStorageService.getItem('errorLog');
clearEntireSession
function is useful for managing the user’s session data. For example, when a user logs out or their session expires, you can call this function to clear all session-related data. // When the user logs out or the session expires sessionStorageService.clearEntireSession();
In conclusion, we have created a generic session storage service in Angular that provides a convenient and reusable way to interact with the browser’s session storage. This service offers a set of functions for storing, retrieving, and managing data in session storage.
Overall, the SessionStorageService
simplifies session storage interactions in Angular, promotes code reusability, and enhances error handling, making it a valuable addition to your application for managing temporary data across user sessions.
WRITTEN BY
Yashlin Naidoo