Using IndexedDB for Local Data Storage
Demonstrate how to use IndexedDB for storing and retrieving data locally in an Angular application to enable full offline functionality.
// Open/create a database named 'myDatabase'
var openRequest = indexedDB.open('myDatabase', 1);
openRequest.onupgradeneeded = function(e) {
var db = e.target.result;
// Create an object store named 'items' if it's not already there
if (!db.objectStoreNames.contains('items')) {
db.createObjectStore('items', { keyPath: 'id', autoIncrement: true });
}
};
This code opens a connection to an IndexedDB database named 'myDatabase' and creates an object store named 'items' if it doesn't already exist. The object store uses 'id' as the primary key and auto-increments it for new entries.
openRequest.onsuccess = function(e) {
var db = e.target.result;
// Start a new transaction
var transaction = db.transaction(['items'], 'readwrite');
var store = transaction.objectStore('items');
// Add data to the store
var data = { name: 'Item 1', description: 'This is an item.' };
var request = store.add(data);
request.onsuccess = function() {
console.log('Data added to the store');
};
};
After successfully opening/creating the database, this code starts a new transaction on the 'items' object store in 'readwrite' mode. It then adds a new item to the store and logs a message when the data is successfully added.
openRequest.onerror = function(e) {
console.error('Error opening database:', e.target.errorCode);
};
This code handles any errors that occur when opening the database, logging the error code to the console.
function getItem(db, id) {
return new Promise((resolve, reject) => {
var transaction = db.transaction(['items'], 'readonly');
var store = transaction.objectStore('items');
var request = store.get(id);
request.onsuccess = function(e) {
resolve(e.target.result);
};
request.onerror = function(e) {
reject('Error fetching data: ' + e.target.errorCode);
};
});
}
This function retrieves an item from the 'items' object store by the given id. It wraps the IndexedDB operations within a Promise to provide an asynchronous API.
// Usage of getItem()
openRequest.onsuccess = function(e) {
var db = e.target.result;
getItem(db, 1).then(item => {
console.log('Retrieved item:', item);
}).catch(err => {
console.error(err);
});
};
When the database is successfully opened, this code demonstrates the usage of the getItem() function to fetch an item with id 1 from the 'items' object store and log the results or catch and log any errors.