Search code examples
angularservice-workerangular-service-worker

Prefetch API data (dataGroups) using Angular Service Worker


I have an Angular website that needs to work offline. Part of what it needs is some data from the API. This can be stale data, so my strategy is to try the API, if that fails, then get it from the cache.

I set this up using the dataGroups:

"dataGroups": [
    {
        "name": "offlineData",
        "urls": [ "/api/offline" ],
        "cacheConfig": {
            "maxSize": 1000,
            "maxAge": "100d",
            "timeout": "500u",
            "strategy": "freshness"
        }
    }
]

However, if a user installs the app (using the manifest), and immediately go offline, the API data doesn't exist in the cache as dataGroups doesn't prefetch.

So where is the correct place that I should hook into and fetch the data? I've tried in the app.component, and in the ServiceWorker Update Service (which is really the same as the app.component as it gets called from there).

Either way, this seems to call the API before the service worker configuration has been processed, so it doesn't get added to the cache.

What is the appropriate lifecycle hook to add this to, so that it performans a prefetch which the ngsw config will then be aware of?


Solution

  • on the initialization of the app, you can add your data to the localstorage. localstorage stores the data tab wise. That means each tab would have their specific data in the localstorage.

    So when the api fails due to network connection. You can use the data stored in the localstorage.