我使用 PWA Service Worker 创建了一个 Angular 应用程序,它也可以离线工作。 但我一直坚持在应用程序离线工作时将数据存储在indexDB中,并希望在应用程序在线工作时使用indexDB数据访问API。
问题1:当应用程序离线运行时,无法将数据存储到indexDB中。 问题2:当应用程序在线运行时,已存储在indexDB中的数据应该打到API并存储在API中。
归档此内容需要遵循三个主要步骤。
首先您需要在 IndexedDB 中创建一个数据库和对象存储来存储您的数据。
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });
};
第二:接下来你需要将数据存储在你刚刚使用上面的代码块创建的IndexedDB中,(当离线时):
if (!navigator.onLine) {
const db = await openDatabase();
const transaction = db.transaction('myObjectStore', 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
const data = { id: 1, name: 'John Doe' };
objectStore.add(data);
}
第三步:接下来再次上线时返回 api 并传递数据:
window.addEventListener('online', async () => {
const db = await openDatabase();
const transaction = db.transaction('myObjectStore', 'readonly');
const objectStore = transaction.objectStore('myObjectStore');
//const data = await objectStore.getAll();
// all the logic to send data to API ,for that probably you are going to
//use angular HttpClient
});
如果有任何错误或任何错误,请告诉我。