简体   繁体   English

workbox.backgroundSync.Plugin 不创建 IndexedDB

[英]workbox.backgroundSync.Plugin doesn't create IndexedDB

I have transformed my Angular app into a PWA.我已将我的 Angular 应用程序转换为 PWA。 The Angular service worker does its job and caches static resources so that the app shell is loaded when being offline. Angular 服务工作者完成其工作并缓存 static 资源,以便在离线时加载应用程序 shell。

Now, I also want to cache POST requests that shall be sent as soon as the device is back online.现在,我还想缓存 POST 请求,这些请求将在设备重新上线后立即发送。 Unfortunately, the Angular service worker does not support HTTP methods other than GET and HEAD.不幸的是,Angular service worker 不支持除 GET 和 HEAD 之外的 HTTP 方法。 Therefore, I'm using Google's workbox library.因此,我使用的是 Google 的工作箱库。

Following the official 'Basic Usage' snippet [1], I've used the workbox.backgroundSync.Plugin() and defined the routes to be cached:按照官方的“基本用法”片段 [1],我使用了 workbox.backgroundSync.Plugin() 并定义了要缓存的路由:

sw.js: sw.js:

importScripts('ngsw-worker.js');
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.0.0/workbox-sw.js')

console.log(`Yay! Workbox is loaded 🎉`);
const bgSyncPlugin = new workbox.backgroundSync.Plugin('http-queue');

workbox.routing.registerRoute(
  /.*/,
  new workbox.strategies.NetworkOnly({plugins: [bgSyncPlugin]}),
  'POST'
);

track.service.ts:跟踪服务.ts:

addTrack(track: Track): Observable<Track> {
  return this.http.post<Track>(`https://backend/track`, track);
}

Workbox is loaded, but, when performing POST requests while being offline, no IndexedDB is created. Workbox 已加载,但在离线时执行 POST 请求时,不会创建 IndexedDB。 Using the Fetch API instead of the Angular HTTP client works neither.使用 Fetch API 而不是 Angular HTTP 客户端不起作用。

[1] https://developers.google.com/web/tools/workbox/modules/workbox-background-sync [1] https://developers.google.com/web/tools/workbox/modules/workbox-background-sync

Your first argument to registerRoute is /\*/ which is a regular expression matching a literal "*". registerRoute 的第一个参数是/\*/ ,它是一个匹配文字“*”的正则表达式。 So it's not matching anything else.所以它不匹配其他任何东西。

Change that to /.*/将其更改为/.*/

Can't tell what causes the problem, but commenting out the Angular service worker in the first line solves the problem.不知道是什么导致了问题,但是在第一行注释掉 Angular service worker 解决了问题。 Apparently, it's not a good idea to mix the Angular service worker and workbox.显然,将 Angular service worker 和 workbox 混用并不是一个好主意。 Maybe it's my use of the background sync plugin.也许是我使用了后台同步插件。 For now, I will use workbox for my service worker - at least until the Angular service worker allows background sync.现在,我将为我的 service worker 使用 workbox - 至少在 Angular service worker 允许后台同步之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM