How to add URL dynamically to angular service worker DataGroup

2.6k Views Asked by At

I am using @angular/service-worker to build a PWA application. Angular service-worker adds the ngsw-config.json file, in which you can add a "dataGroups" section to configure cache urls and strategy, etc.

    "dataGroups": [{
    "name": "tile-cache",
    "urls": [
    ],
    "cacheConfig": {
      "strategy": "performance",
      "maxSize": 10000,
      "maxAge": "30d"
    }
  }].

In my application, I need to add cached urls(like some external map tiles urls) dynamically to the service worker CacheStorage instead of pre-configuring them in dataGroups of the ngsw-config.json file.

I don't see @angular/service-worker exposing any public class or method for doing this. Is there anyone who knows how to achieve this?

2

There are 2 best solutions below

0
On

Looking at the source code for angular service worker there aren't many options for what you want to do. All you have control over is the script path when you're importing ServiceWorkerModule into your app module. You can potentially change the script path based on the environment or other factors.

According to the service worker config docs you can use url patterns in your ngsw-config.json. There must be some pattern(s) to the map tiles urls you can define for the dataGroup so you don't have to dynamically/programmatically add the cached urls.

0
On

in Angular service worker, there is very limited configuration option is available so, I think you need to modify/update the ngsw-config.json using nodejs script, you need to run the script before build your project.