我使用 @angular/service-worker
模块来生成一个服务 worker 来缓存我的 Angular 7 应用程序的所有静态 Assets 并且它运行良好(在 chrome 开发工具的网络选项卡中,这些文件被标记为 from ServiceWorker
)。
我想做的是为从外部 API 获取的数据添加缓存支持(和后台同步)。我知道 @angular/service-worker
模块支持 dataGroups
类型的 Assets ,但我想做一些更复杂的事情:首先提供缓存数据,然后通过网络获取数据,更新缓存并最终返回第二个更新的响应。这个想法在离线食谱中有描述:https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-then-network
所以我需要添加一个与 Angular 生成的自定义软件共存的自定义软件。问题是我的 fetch
事件监听器从未被触发。
我注册我的服务人员:
ServiceWorkerModule.register('../sw.js', { enabled: environment.production }),
在 app.module.ts 中。
sw.js 文件导入 ngsw-worker.js(由 Angular 生成):
importScripts('./ngsw-worker.js');
importScripts('./sw-custom.js');
然后,sw-custom.js
在 install
和 fetch
上添加两个事件监听器:
self.addEventListener('install', function(event) {
try {
console.log('typeof System in install', typeof System);
} catch(e){}
console.log('caching');
event.waitUntil(
caches.open(CACHE_VERSION).then(function(cache) {
console.log('caching - getting');
return;
}).catch(function(error){ console.log('error', error) })
);
});
self.addEventListener('fetch', event => {
console.log('Hello service worker');
if (event.request.method !== 'GET') return;
const request = event.request.clone();
// Do stuff
event.respondWith(fetch(request));
});
install
事件的监听器被执行,但 fetch
事件没有执行,我不明白为什么。
最佳答案
问题是您首先要导入 Angular ngsw-worker.js
,它包含自己的监听器,可以防止您的监听器被执行。
尝试像这样更改导入顺序:
importScripts('./sw-custom.js');
importScripts('./ngsw-worker.js');
此外,您可能需要通过停止事件传播来避免运行 Angular 生成的监听器,避免重复获取之类的事情:
self.addEventListener('fetch', event => {
console.log('Hello service worker');
if (event.request.method !== 'GET') return;
const request = event.request.clone();
// Do stuff
event.respondWith(fetch(request));
// stop propagation to Angular Service Worker if we need
event.stopImmediatePropagation();
});
关于angular - 服务 worker : fetch event listener is never triggered by HTTP GET requests to an API on Angular 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54626481/