Angular SessionStorage
Session Storage is a web storage API that allows temporary data to be stored in a user's browser and remain available between browser sessions. In Angular, you can use the sessionStorage
service to store data in the session storage.
Syntax
sessionStorage.setItem("key", "value");
const value = sessionStorage.getItem("key");
sessionStorage.removeItem("key");
Example
import { Component } from '@angular/core';
@Component({
selector: 'app-storage',
template: `
<button (click)="storeData()">Store Data</button>
<button (click)="retrieveData()">Retrieve Data</button>
<button (click)="clearData()">Clear Data</button>
`
})
export class StorageComponent {
storeData() {
sessionStorage.setItem('myKey', 'Hello World!');
}
retrieveData() {
const value = sessionStorage.getItem('myKey');
console.log(value);
}
clearData() {
sessionStorage.removeItem('myKey');
}
}
Output
When the Store Data
button is clicked, the string "Hello World!" is stored in the session storage under the key myKey
.
When the Retrieve Data
button is clicked, the string "Hello World!" is retrieved from the session storage and logged to the console.
When the Clear Data
button is clicked, the string "Hello World!" is removed from the session storage.
Explanation
Angular's sessionStorage
service provides a simple API for interacting with the browser's session storage. The setItem
method is used to store data in the session storage, the getItem
method is used to retrieve data from the session storage, and the removeItem
method is used to remove data from the session storage.
Use
Session storage is useful for storing data that needs to be available across multiple pages or browser sessions. This can include user preferences, form data, and application state.
Important Points
- Data stored in session storage is not permanent and will be deleted when the browser is closed.
- You can only store key-value pairs as strings in session storage.
- Avoid storing sensitive information in session storage as it is not a secure storage mechanism.
Summary
Angular's sessionStorage
service provides an easy way to store and retrieve temporary data in the user's browser. This can be useful for storing application state or user preferences that need to be maintained across multiple page requests. However, remember that session storage has limitations and is not a secure storage mechanism for sensitive data.