【发布时间】:2021-09-28 00:45:16
【问题描述】:
我想在缓存中保存一些来自 API 的数据,以防我失去显示数据的连接
我有一个工作部件列表,所以如果我离线我想继续查看这些部件,因为当我再次进入组件时,它会调用 API 并再次带来它们,因为没有连接,它在这里留下白色将是从缓存中带来它们
import {precacheAndRoute} from 'workbox-precaching';
import {clientsClaim, skipWaiting} from 'workbox-core';
import {registerRoute} from 'workbox-routing';
import {CacheFirst, NetworkFirst, NetworkOnly, StaleWhileRevalidate} from 'workbox-strategies';
import {CacheableResponsePlugin} from "workbox-cacheable-response";
import {BackgroundSyncPlugin} from 'workbox-background-sync';
import {Queue} from 'workbox-background-sync';
declare const self: ServiceWorkerGlobalScope;
skipWaiting();
clientsClaim();
const queue = new Queue('cola');
const bgSyncPlugin = new BackgroundSyncPlugin('api-cola', {
onSync: async ({queue}) => {
let entry;
while ((entry = await queue.shiftRequest())) {
try {
let clone = entry.request.clone();
await fetch(clone);
console.error("Replay successful for request", entry.request);
} catch (error) {
console.error("Replay failed for request", entry.request, error);
// Put the entry back in the queue and re-throw the error:
await queue.unshiftRequest(entry);
throw error;
}
}
console.log("Replay complete!");
}
});
registerRoute(
/\/api\/.*\/*.php/,
new NetworkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);
registerRoute(
({url}) => url.origin === 'https://xxx.xxx.com' &&
url.pathname.startsWith('/api/'),
new CacheFirst({
cacheName: 'api-cache',
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200, 404],
})
]
})
);
registerRoute(
/assets\/images\/icons\/icon-.+\.png$/,
new CacheFirst({
cacheName: 'icons'
})
);
precacheAndRoute(self.__WB_MANIFEST);
当您在恢复连接时离线时,同步已完成并且工作正常。
【问题讨论】:
-
你能澄清什么是不工作吗?目前还不清楚问题是什么。
标签: service-worker workbox angular-service-worker