Introduction:
As web applications become more complex, the need to store data locally has become increasingly important. One way to achieve this is by using local storage in Angular applications. Local storage is a key-value storage system that allows developers to store data in the user’s browser. In this article, we’ll explore how local storage works in Angular and provide practical examples to help you understand its usage.
Understanding Local Storage in Angular:
Local storage is a feature of modern web browsers that allows you to store data locally on a user’s device. This data is stored as key-value pairs and can be accessed using JavaScript. In Angular, local storage can be used to store user preferences, such as their preferred language or theme, or to store data for use in other parts of the application.
To use local storage in an Angular application, you first need to import the localStorage
object from the window
object. Here’s an example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'my-app';
ngOnInit() {
// Store data in local storage
localStorage.setItem('key', 'value');
// Retrieve data from local storage
const data = localStorage.getItem('key');
console.log(data); // Output: value
}
}
In this example, we’re importing the localStorage
object from the window
object and using the setItem
method to store a key-value pair in local storage. We then use the getItem
method to retrieve the value of the key and log it to the console.
Here is the video tutorial
Real-Life Example: Shopping Cart
Let’s say you’re building an e-commerce application and you want to allow users to add items to their shopping cart. One way to achieve this is by using local storage to store the user’s cart data. Here’s an example of how you can implement this in Angular:
import { Component } from '@angular/core';
interface Product {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css'],
})
export class CartComponent {
cart: Product[] = [];
constructor() {
const data = localStorage.getItem('cart');
if (data) {
this.cart = JSON.parse(data);
}
}
addToCart(product: Product) {
this.cart.push(product);
localStorage.setItem('cart', JSON.stringify(this.cart));
}
clearCart() {
this.cart = [];
localStorage.removeItem('cart');
}
}
In this example, we’re creating an Product
interface to represent the product data, and we’re using a CartComponent
to manage the user’s shopping cart. When the component is initialized, we’re using the getItem
method to retrieve the cart data from local storage, and we’re parsing it as JSON.
We’re also providing two methods, addToCart
and clearCart
, to add and remove items from the cart. When the user adds an item to the cart, we’re using the push
method to add it to the cart array, and we’re using the setItem
method to store the updated cart data in local storage. Similarly, when the user clears the cart, we’re using the removeItem
method to remove the cart data from local storage.
What happens if a browser is not supported for local storage?
To check if the user’s browser supports local storage before using it in an Angular application, you can use the localStorage
object’s getItem()
method to check if the browser throws an error when attempting to access local storage. Here’s an example:
if (typeof localStorage !== 'undefined') {
// Local storage is supported
localStorage.setItem('key', 'value');
const data = localStorage.getItem('key');
console.log(data); // Output: value
} else {
// Local storage is not supported
console.log('Local storage is not supported');
}
In this example, we’re first checking if the localStorage
object exists by checking its type. If it exists, we’re using the setItem()
and getItem()
methods to store and retrieve data from local storage. If it doesn’t exist, we’re logging a message to the console to indicate that local storage is not supported.
How to make this storage unique per user?
To make the local storage unique per user, you can include a unique identifier for each user in the key name used to store the data in local storage. This unique identifier could be the user’s username, email address, or unique user ID.
For example, you could modify the set()
and get()
methods to accept a userId
parameter and append it to the key name:
export class LocalStorageService {
constructor() {}
set(key: string, value: any, userId: string): void {
localStorage.setItem(`${key}_${userId}`, JSON.stringify(value));
}
get(key: string, userId: string): any {
const value = localStorage.getItem(`${key}_${userId}`);
return value ? JSON.parse(value) : null;
}
}
With this modification, data stored in local storage will be unique to each user, based on their userId
. When retrieving data from local storage, make sure to pass the correct userId
to the get()
method.
Application Source Code @ LearnSmartCoding GitHub
Check out other topics that might interest you.
- How to Implement reCAPTCHA in an Angular Application: A Step-by-Step Guide
- How to Show a Warning Message to Users When They Try to Close Your Website
- Lazy Loading in Angular: Boosting Performance and User Experience
- Understanding the CanLoad Guard in Angular: Real-time Example
- How to Use Multiple Angular AuthGuards in canActivate | Step-by-Step Guide
- Angular Custom Directives: A Beginner’s Guide with Real-Time Scenario
- Upload Files and Model Data with Angular and .NET Core Web API to Single Endpoint
- Boosting Performance in Your .NET Core Application with Caching
Conclusion:
Local storage is a powerful feature that can be used to enhance the user experience in Angular applications. By using local storage, you can store user data.