Search code examples
angularprogressive-web-appsworkboxbackground-sync

workbox.backgroundSync.Plugin doesn't create IndexedDB


I have transformed my Angular app into a PWA. The Angular service worker does its job and caches static resources so that the app shell is loaded when being offline.

Now, I also want to cache POST requests that shall be sent as soon as the device is back online. Unfortunately, the Angular service worker does not support HTTP methods other than GET and HEAD. Therefore, I'm using Google's workbox library.

Following the official 'Basic Usage' snippet [1], I've used the workbox.backgroundSync.Plugin() and defined the routes to be cached:

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:

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. Using the Fetch API instead of the Angular HTTP client works neither.

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


Solution

  • Can't tell what causes the problem, but commenting out the Angular service worker in the first line solves the problem. Apparently, it's not a good idea to mix the Angular service worker and 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.